前提条件引用对应的jar
<!-- https://mvnrepository.com/artifact/org.apache.poi/poi-scratchpad --> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-scratchpad</artifactId> <version>4.1.2</version> </dependency> <!-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml --> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>4.1.2</version> </dependency>
public static void main(String[] args) { XWPFDocument document=new XWPFDocument(); String str = "1.登录环境 (1)使用XXX账号登录(2)XXXXXXXXXXXXXXXXXXXXXXXXXX(3)XXXXXXXXXXX(4)2XXXXXXXXXXX;2.选择XXXX(1)检查属性XXXXXX (2)检查属性XXXXXXX(3)11检查属性XXXXX;3.检查数据能不能显示(1)显示的数据是否正确"; Map<String, String> map = new HashMap<String, String>(); String[] str1 = str.split(";"); //先按照;号进行切割字符串 for (String sValue : str1) {//遍历分割后的字符串,再按照.进行分割且长度2,将切割的数据放入到Map集合中 String[] value = sValue.split("\\.", 2); if (value.length == 2) { map.put(value[0], value[1]); } } int size= map.size();//确定创建table需要几行几列 XWPFTable xTable= document.createTable(size+1,3); //table表头 xTable.getRow(0).getCell(0).setText("序号"); xTable.getRow(0).getCell(1).setText("内容"); xTable.getRow(0).getCell(2).setText("截图"); int i=1; //遍历map集合将Value写入到对应单元格 for (String key: map.keySet()) { xTable.getRow(i).getCell(0).setText(key); //写入对应序号 String value= map.get(key); String[] str2= value.split("\\("); //再次按照(分割,遇到(就开始换行 for (String values:str2) { //获取哪一行和那一列单元格 XWPFTableCell cellToSplit= xTable.getRow(i).getCell(1); XWPFParagraph newPara = cellToSplit.addParagraph(); // 在原单元格中添加一个新的段落 XWPFRun newRun = newPara.createRun(); // 创建一个新的文本运行 newRun.setText(values); } xTable.getRow(i).getCell(2).setText(" "); i++; } try { FileOutputStream fos=new FileOutputStream("/Users/mac/soft/123/myDoc.docx"); document.write(fos); fos.close(); document.close(); }catch ( IOException e){ } } }
将表格中的每一步数据,都是换行显示,方便美观