300字范文,内容丰富有趣,生活中的好帮手!
300字范文 > POI 实现Word表格合并单元格(行合并)

POI 实现Word表格合并单元格(行合并)

时间:2019-12-22 02:34:22

相关推荐

POI 实现Word表格合并单元格(行合并)

1 Maven依赖

<dependency><groupId>com.alibaba</groupId><artifactId>easyexcel</artifactId><version>2.2.7</version></dependency><dependency><groupId>cn.hutool</groupId><artifactId>hutool-all</artifactId><version>5.6.2</version></dependency>

2 合并单元格

/*** 合并单元格** @param table 表格对象* @param beginRowIndex 开始行索引* @param endRowIndex 结束行索引* @param colIndex合并列索引*/public static void mergeCell(XWPFTable table, int beginRowIndex, int endRowIndex, int colIndex) {if (beginRowIndex == endRowIndex || beginRowIndex > endRowIndex) {return;}//合并行单元格的第一个单元格CTVMerge startMerge = CTVMerge.Factory.newInstance();startMerge.setVal(STMerge.RESTART);//合并行单元格的第一个单元格之后的单元格CTVMerge endMerge = CTVMerge.Factory.newInstance();endMerge.setVal(STMerge.CONTINUE);table.getRow(beginRowIndex).getCell(colIndex).getCTTc().getTcPr().setVMerge(startMerge);for (int i = beginRowIndex + 1; i <= endRowIndex; i++) {table.getRow(i).getCell(colIndex).getCTTc().getTcPr().setVMerge(endMerge);}}

3 调试代码

/*** 合并单元格** @param response*/@GetMapping("/mergeCell")public void mergeCell(HttpServletResponse response) {try {//读文件ClassPathResource cpr = new ClassPathResource("/doc/模板合并单元格.docx");XWPFDocument document = new XWPFDocument(cpr.getInputStream());mergeCell(document.getTableArray(0), 1, 2, 0);//返回流response.setHeader("content-type", "application/octet-stream");response.setContentType("application/octet-stream;charset=UTF-8");response.setHeader("Content-Disposition", "attachment; filename=" + new String("模板.docx".getBytes("utf-8"), "ISO-8859-1"));OutputStream outputStream = response.getOutputStream();document.write(outputStream);outputStream.flush();outputStream.close();} catch (Exception e) {e.printStackTrace();}}

4 模板文件

模板路径:

模板内容:

5 调试结果

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。