Java使用ApachePOI库导出word文档,使用该库的XWPFDocument类,可以实现word文档的读写操作。
一、创建Word文档并添加内容 {#title-1}
使用XWPFDocument创建空Word文档,并使用XWPFParagraph创建段落,然后通过XWPFRun将文本添加到段落中。
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;
public class CreateWord {
public static void main(String[] args) {
XWPFDocument document = new XWPFDocument();
XWPFParagraph paragraph = document.createParagraph();
XWPFRun run = paragraph.createRun();
run.setText("Hello, World!");
}
}
接着保存创建的Word文档。
import java.io.FileOutputStream;
import java.io.IOException;
// adding the rest of the code
public class CreateWord {
public static void main(String[] args) {
// create an empty document
XWPFDocument document = new XWPFDocument();
// create a paragraph
XWPFParagraph paragraph = document.createParagraph();
// add text to the paragraph
XWPFRun run = paragraph.createRun();
run.setText("Hello, World!");
// write the document to a file
try {
document.write(new FileOutputStream("HelloWorld.docx"));
} catch(IOException e) {
e.printStackTrace();
} finally {
try {
document.close();
} catch(IOException e) {
e.printStackTrace();
}
}
}
}
二、对Word文档的更多操作 {#title-2}
除了添加文本内容外,还可以对Word文档进行更多的操作,如插入图片、调整字体样式等。
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;
public class Example {
public static void main(String[] args) {
XWPFDocument document = new XWPFDocument();
XWPFParagraph paragraph = document.createParagraph();
XWPFRun run = paragraph.createRun();
// Set text color
run.setColor("FF0000");
// Set text size to 14
run.setFontSize(14);
// Set text style to bold
run.setBold(true);
run.setText("Hello, World!");
}
}
这段代码将创建一个红色的、字号为14、粗体的文本。
三、插入图片 {#title-3}
以下是插入图片的示例代码:
import java.io.FileInputStream;
import java.io.IOException;
import org.apache.poi.xwpf.usermodel.Document;
import org.apache.poi.xwpf.usermodel.*;
public class AddImage {
public static void main(String[] args) {
XWPFDocument doc = new XWPFDocument();
XWPFParagraph p = doc.createParagraph();
XWPFRun r = p.createRun();
try {
int format = Document.PICTURE_TYPE_JPEG;
r.addPicture(new FileInputStream("my_picture.jpg"), format);
} catch (IOException e) {
e.printStackTrace();
}
}
}