java写入word表格数据进行分割和换行

前提条件引用对应的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){

}
    }
    }

将表格中的每一步数据,都是换行显示,方便美观

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值