word 后缀有doc、docx。今天只写了docx的。写的不好,大家多指教
maven管理,pom文件添加了依赖
<!-- https://mvnrepository.com/artifact/org.apache.poi/poi --> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>4.1.2</version> </dependency> <!-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml-schemas --> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml-schemas</artifactId> <version>4.1.2</version> </dependency>
文件内容:乱敲的
1.读取本地文件word文档,获取内容,代码如下: @Test public void read(){ FileInputStream is = null; XWPFDocument xwpfDocument = null; try { is = new FileInputStream("D:\\uploads\\test.docx"); xwpfDocument = new XWPFDocument(is); XWPFWordExtractor xwpfWordExtractor = new XWPFWordExtractor(xwpfDocument); String text = xwpfWordExtractor.getText(); System.out.println(text); } catch (IOException e) { throw new RuntimeException(e); } finally { try { is.close(); } catch (IOException e) { throw new RuntimeException(e); } } }
效果:
2.在本地新建word,写入内容
@Test public void write1(){ //创建word文件 XWPFDocument document = new XWPFDocument(); FileOutputStream os = null; try { os = new FileOutputStream("d://uploads//2.docx"); //创建个段落 XWPFParagraph paragraph = document.createParagraph(); XWPFRun run = paragraph.createRun(); //写入内容 run.setText("HELLO!我是一个中国人,我爱我的祖国!"); run.setBold(true); run.setColor("ff0000"); run.setItalic(true); //创建表格 XWPFTable tab = document.createTable(); tab.setWidth(5000); // 表格宽度 //第一行 XWPFTableRow row = tab.getRow(0); row.setHeight(1000); // 表格高度 //创建列 row.getCell(0).setText("Sl.No."); row.addNewTableCell().setText("Name"); row.addNewTableCell().setText("Email"); //第二行 row = tab.createRow(); row.getCell(0).setText("1."); row.getCell(1).setText("eric"); row.getCell(2).setText("eric@gmail.com"); //第三行 row = tab.createRow(); row.getCell(0).setText("2."); row.getCell(1).setText("jack"); row.getCell(2).setText("jack@gmail.com"); document.write(os); } catch (IOException e) { throw new RuntimeException(e); } finally { try { os.close(); } catch (IOException e) { throw new RuntimeException(e); } } }
效果: