开始写代码
word 97-03版本是用.doc后缀 用HWPF
07-19版本是用.docx后缀 用XWPF
对应的是两套函数方法
创建Word,写入内容。源代码
package my; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import org.apache.poi.openxml4j.exceptions.InvalidFormatException; import org.apache.poi.util.Units; import org.apache.poi.xwpf.usermodel.ParagraphAlignment; import org.apache.poi.xwpf.usermodel.UnderlinePatterns; import org.apache.poi.xwpf.usermodel.XWPFDocument; import org.apache.poi.xwpf.usermodel.XWPFParagraph; import org.apache.poi.xwpf.usermodel.XWPFRun; public class test { public static void main(String[] args) throws InvalidFormatException { // TODO Auto-generated method stub System.out.println("开始"); //Word路径 File file = new File("D:\\1\\2\\123.docx"); //png路径 File filePng = new File("D:\\1\\2\\阿飞头像.png"); //创建一个文档 HWPFDocument , *.docx 对应XWPFDocument //*.doc对应 XWPFDocument doc = new XWPFDocument(); //添加一个段落 XWPFParagraph p1 = doc.createParagraph(); p1.setAlignment(ParagraphAlignment.CENTER); //添加一句 XWPFRun r1 = p1.createRun(); r1.setBold(true); r1.setText("你好JAVA"); r1.setBold(true); r1.setFontFamily("Courier"); r1.setFontSize(20); //在添加一句 XWPFRun r2 = p1.createRun(); r2.setBold(false); r2.setText("2021年5月21日"); r2.setBold(true); r2.setFontFamily("Courier"); r2.setUnderline(UnderlinePatterns.DASH); r2.setColor("FF0000"); //在添加一个段落 XWPFParagraph p2 = doc.createParagraph(); p2.setAlignment(ParagraphAlignment.CENTER); //添加一句 XWPFRun r = p2.createRun(); r.setBold(true); r.setText(filePng.getName()); r.setBold(true); r.setFontFamily("Courier"); r.setFontSize(20); r.addBreak(); //输出到文件 try { //添加一个图片 InputStream stream = new FileInputStream(filePng); r.addPicture(stream, XWPFDocument.PICTURE_TYPE_PNG, //图像格式 filePng.getAbsolutePath(), //文件全路径 Units.toEMU(350), Units.toEMU(350));//350x350 pixels stream.close(); r.addBreak(); FileOutputStream out = new FileOutputStream(file); doc.write(out); out.close(); }catch(IOException e) { e.printStackTrace(); } System.out.println("结束"); } }
演示