word 插入表格(转载csdn)https://blog.youkuaiyun.com/RR369_yyh/article/details/79693946

本文介绍了一种使用Java和Apache POI库动态生成并修改Word文档的方法,通过读取模板文件,替换文本内容,自动生成表格,并调整表格样式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

package com.controller;
 
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.math.BigInteger;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
 
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;
import org.apache.poi.xwpf.usermodel.XWPFTable;
import org.apache.poi.xwpf.usermodel.XWPFTableRow;
import org.apache.xmlbeans.XmlCursor;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTJc;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTbl;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTblPr;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTblWidth;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.STJc;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.STTblWidth;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
 
@Controller
@RequestMapping(value="/base")  
public class TestController {
    
    @RequestMapping(value="/test")
    public void docTest()   {
        String templatePath = "D:\\demo.doc";
        InputStream in = null;
        OutputStream out = null;
        try {
            in = new FileInputStream(templatePath);
            XWPFDocument doc = new XWPFDocument(in);
            //文本替换
            Map<String, String> param = new HashMap<String, String>();
            param.put("PartyA", "我是甲方");
            param.put("PartyB", "我是乙方");
            param.put("date", new SimpleDateFormat("yyyy-MM-dd").format(new Date()));
            param.put("text", "合同内容合同内容合同内容合同内容合同内容合同内容合同内容合同内容合同内容合同内容合同内容合同内容合同内容");
            List<XWPFParagraph> allXWPFParagraphs = doc.getParagraphs();
            for (XWPFParagraph xwpfParagraph : allXWPFParagraphs) {
                List<XWPFRun> runs = xwpfParagraph.getRuns();
                for (XWPFRun run : runs) {
                    String text = run.getText(0);
                    if (StringUtils.isNoneBlank(text)) {
                        if (text.equals("table")) {
                            //表格生成 6行5列.
                            int rows = 6;
                            int cols = 5;
                            XmlCursor cursor = xwpfParagraph.getCTP().newCursor();
                            XWPFTable tableOne = doc.insertNewTbl(cursor);
                            
                            //样式控制
                            CTTbl ttbl = tableOne.getCTTbl();
                            CTTblPr tblPr = ttbl.getTblPr() == null ? ttbl.addNewTblPr() : ttbl.getTblPr();  
                            CTTblWidth tblWidth = tblPr.isSetTblW() ? tblPr.getTblW() : tblPr.addNewTblW();  
                            CTJc cTJc = tblPr.addNewJc();  
                            cTJc.setVal(STJc.Enum.forString("center"));//表格居中
                            tblWidth.setW(new BigInteger("9000"));//每个表格宽度
                            tblWidth.setType(STTblWidth.DXA);  
                            
                            //表格创建
                            XWPFTableRow tableRowTitle = tableOne.getRow(0);
                            tableRowTitle.getCell(0).setText("标题");
                            tableRowTitle.addNewTableCell().setText("内容");
                            tableRowTitle.addNewTableCell().setText("姓名");
                            tableRowTitle.addNewTableCell().setText("日期");
                            tableRowTitle.addNewTableCell().setText("备注");
                            for (int i = 1; i < rows; i++) {
                                XWPFTableRow createRow = tableOne.createRow();
                                for (int j = 0; j < cols; j++) {
                                    createRow.getCell(j).setText("我是第"+i+"行,第"+(j+1)+"列");
                                }
                            }
                            run.setText("", 0);
                        }else {
                            for (Entry<String, String> entry : param.entrySet()) {
                                String key = entry.getKey();
                                if (text.indexOf(key) != -1) {
                                    text = text.replace(key, entry.getValue());
                                    run.setText(text, 0);
                                }
                            }
                        }
                    }
                }
            }
            
            out = new FileOutputStream("D:\\report.doc");
            // 输出
            doc.write(out);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
 
}

demo.doc 如下:

report.doc 如下:

yyh@yyh:~$ sudo apt install libmodbus5 libmodbus-dev -y 正在读取软件包列表... 完成 正在分析软件包的依赖关系树 正在读取状态信息... 完成 下列【新】软件包将被安装: libmodbus-dev libmodbus5 升级了 0 个软件包,新安装了 2 个软件包,要卸载 0 个软件包,有 62 个软件包未被升级。 需要下载 111 kB 的归档。 解压缩后会消耗 313 kB 的额外空间。 获取:1 http://mirrors.tuna.tsinghua.edu.cn/ubuntu focal/universe amd64 libmodbus5 amd64 3.1.6-2 [23.5 kB] 获取:2 http://mirrors.tuna.tsinghua.edu.cn/ubuntu focal/universe amd64 libmodbus-dev amd64 3.1.6-2 [87.6 kB] 已下载 111 kB,耗时 7秒 (17.0 kB/s) 正在选中未选择的软件包 libmodbus5:amd64。 (正在读取数据库 ... 系统当前共安装有 185694 个文件和目录。) 准备解压 .../libmodbus5_3.1.6-2_amd64.deb ... 正在解压 libmodbus5:amd64 (3.1.6-2) ... 正在选中未选择的软件包 libmodbus-dev:amd64。 准备解压 .../libmodbus-dev_3.1.6-2_amd64.deb ... 正在解压 libmodbus-dev:amd64 (3.1.6-2) ... 正在设置 libmodbus5:amd64 (3.1.6-2) ... 正在设置 libmodbus-dev:amd64 (3.1.6-2) ... 正在处理用于 man-db (2.9.1-1) 的触发器 ... 正在处理用于 libc-bin (2.31-0ubuntu9.17) 的触发器 ... /sbin/ldconfig.real: /usr/local/cuda/targets/x86_64-linux/lib/libcudnn_adv_train .so.8 is not a symbolic link /sbin/ldconfig.real: /usr/local/cuda/targets/x86_64-linux/lib/libcudnn_cnn_infer .so.8 is not a symbolic link /sbin/ldconfig.real: /usr/local/cuda/targets/x86_64-linux/lib/libcudnn_ops_infer .so.8 is not a symbolic link /sbin/ldconfig.real: /usr/local/cuda/targets/x86_64-linux/lib/libcudnn_adv_infer .so.8 is not a symbolic link /sbin/ldconfig.real: /usr/local/cuda/targets/x86_64-linux/lib/libcudnn.so.8 is n ot a symbolic link /sbin/ldconfig.real: /usr/local/cuda/targets/x86_64-linux/lib/libcudnn_cnn_train .so.8 is not a symbolic link /sbin/ldconfig.real: /usr/local/cuda/targets/x86_64-linux/lib/libcudnn_ops_train .so.8 is not a symbolic link yyh@yyh:~$ 安装成功了吗
04-03
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值