一、创建Word文档并添加内容
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文档的更多操作
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、粗体的文本。
三、插入图片
以下是插入图片的示例代码:
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(); } } }