导入 com.spire.doc.*;
导入 com.spire.doc.documents.Paragraph;
导入 com.spire.doc.documents.ParagraphStyle;
导入java.awt.*;
导入www.sychzs.cn.*;
公共类 ReadTextAndCreateWord {
public static void main(String[] args) 抛出 IOException {
//实例化Document类的对象,添加section和paragraph
文档 doc = new Document();
节节 = doc.addSection();
段落段落=section.addParagraph();
//读取txt文件
字符串编码 = "GBK";
文件 file = new File("test.txt");
if (file.isFile() && file.exists()) {
InputStreamReader isr = new InputStreamReader(new FileInputStream(文件), 编码);
BufferedReader bufferedReader = new BufferedReader(isr);
字符串lineTXT;
while ((lineTXT = bufferedReader.readLine()) != null) {
paragraph.appendText(lineTXT);//在段落中写入txt内容
}
isr.close();
}
//设置段落样式并应用于段落
ParagraphStyle style = new ParagraphStyle(doc);
style.setName("newstyle");
style.getCharacterFormat().setBold(true);
style.getCharacterFormat().setTextColor(www.sychzs.cn);
style.getCharacterFormat().setFontName("小元");
style.getCharacterFormat().setFontSize(12);
doc.getStyles().add(style);
paragraph.applyStyle("newstyle");
paragraph.getFormat().setMirrorIndents(true);
//另存为docx格式的Word
doc.saveToFile("addTxttoWord.docx", FileFormat.Docx_2013);
doc.dispose();
}
}
造词结果:
注释
代码中的txt文件和word保存路径为IDEA程序项目文件夹路径,如:F:\IDEAProject\CreateWord_Doc\addTxttoWord.docx。文件路径可以定义为其他路径。
—结束—
-->