博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
java POI往word文档中指定位置插入表格
阅读量:5138 次
发布时间:2019-06-13

本文共 6967 字,大约阅读时间需要 23 分钟。

1.Service  demo

import java.awt.Color;import java.awt.Font;import java.awt.Graphics;import java.awt.image.BufferedImage;import java.io.File;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.DecimalFormat;import java.text.NumberFormat;import java.text.SimpleDateFormat;import java.util.Date;import java.util.Iterator;import java.util.List;import java.util.Map; import org.apache.poi.POIXMLDocument;import org.apache.poi.util.IOUtils;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.XWPFTableCell;import org.apache.poi.xwpf.usermodel.XWPFTableRow;import org.apache.xmlbeans.XmlCursor;import org.docx4j.TraversalUtil;import org.docx4j.dml.wordprocessingDrawing.Inline;import org.docx4j.finders.RangeFinder;import org.docx4j.openpackaging.packages.WordprocessingMLPackage;import org.docx4j.openpackaging.parts.WordprocessingML.BinaryPartAbstractImage;import org.docx4j.openpackaging.parts.WordprocessingML.MainDocumentPart;import org.docx4j.wml.Body;import org.docx4j.wml.CTBookmark;import org.docx4j.wml.Document;import org.docx4j.wml.Drawing;import org.docx4j.wml.ObjectFactory;import org.docx4j.wml.P;import org.docx4j.wml.R;import org.jfree.chart.ChartFactory;import org.jfree.chart.ChartUtilities;import org.jfree.chart.JFreeChart;import org.jfree.chart.labels.StandardPieSectionLabelGenerator;import org.jfree.chart.plot.PiePlot;import org.jfree.data.general.DefaultPieDataset;import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTblPr;import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTblWidth;import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTcPr;import org.springframework.stereotype.Service;import com.google.common.collect.Lists;import com.google.common.collect.Maps; public class ExportBgServiceImpl {    private static final String bookmark = "tpBookmark";// 报告图片位置的书签名            public void exportBg(OutputStream out) {        String srcPath = "D:/tp/fx.docx";        String targetPath = "D:/tp/fx2.docx";        String key = "$key";// 在文档中需要替换插入表格的位置        XWPFDocument doc = null;        File targetFile = null;        try {            doc = new XWPFDocument(POIXMLDocument.openPackage(srcPath));            List
paragraphList = doc.getParagraphs(); if (paragraphList != null && paragraphList.size() > 0) { for (XWPFParagraph paragraph : paragraphList) { List
runs = paragraph.getRuns(); for (int i = 0; i < runs.size(); i++) { String text = runs.get(i).getText(0).trim(); if (text != null) { if (text.indexOf(key) >= 0) { runs.get(i).setText(text.replace(key, ""), 0); XmlCursor cursor = paragraph.getCTP().newCursor(); // 在指定游标位置插入表格 XWPFTable table = doc.insertNewTbl(cursor); CTTblPr tablePr = table.getCTTbl().getTblPr(); CTTblWidth width = tablePr.addNewTblW(); width.setW(BigInteger.valueOf(8500)); this.inserInfo(table); break; } } } } } doc.write(out); out.flush(); out.close(); } catch (Exception e) { throw new SysException(ERRORConstants.COMMON_SYSTEM_ERROR, e); } } /** * 把信息插入表格 * @param table * @param data */ private void inserInfo(XWPFTable table) { List
data = mapper.getInfo();//需要插入的数据 XWPFTableRow row = table.getRow(0); XWPFTableCell cell = null; for (int col = 1; col < 6; col++) {
//默认会创建一列,即从第2列开始 // 第一行创建了多少列,后续增加的行自动增加列 CTTcPr cPr =row.createCell().getCTTc().addNewTcPr(); CTTblWidth width = cPr.addNewTcW(); if(col==1||col==2||col==4){ width.setW(BigInteger.valueOf(2000)); } } row.getCell(0).setText("指标"); row.getCell(1).setText("指标说明"); row.getCell(2).setText("公式"); row.getCell(3).setText("参考值"); row.getCell(4).setText("说明"); row.getCell(5).setText("计算值"); for(DTO item : data){ row = table.createRow(); row.getCell(0).setText(item.getZbmc()); cell = row.getCell(1); cell.getCTTc().addNewTcPr().addNewTcW().setW(BigInteger.valueOf(2000)); cell.setText(item.getZbsm()); cell = row.getCell(2); cell.getCTTc().addNewTcPr().addNewTcW().setW(BigInteger.valueOf(2000)); cell.setText(item.getJsgs()); if(item.getCkz()!=null&&!item.getCkz().contains("$")){ row.getCell(3).setText(item.getCkz()); } cell = row.getCell(4); cell.getCTTc().addNewTcPr().addNewTcW().setW(BigInteger.valueOf(2000)); cell.setText(item.getSm()); row.getCell(5).setText(item.getJsjg()==null?"无法计算":item.getJsjg()); } }}

2.Controller

public void exportBg(HttpServletResponse response) {        try {            response.setContentType("application/octet-stream");            String name = "报告";            response.addHeader("Content-Disposition", "attachment;filename="+new String(name.getBytes(),"iso-8859-1") +".docx");            OutputStream out = response.getOutputStream();            export.exportBg(out,sblsh);         } catch (Exception e) {                    }    }

3.maven 

org.apache.poi
poi-excelant
3.12
org.apache.poi
poi-scratchpad
3.12
org.apache.poi
poi-ooxml
3.8
org.apache.poi
poi-ooxml-schemas
3.8
org.jfree
jfreechart
1.0.19
org.docx4j
docx4j
3.3.1

 

在文档中指定位置  设置好  关键字如  demo 中的 “$key”

结果图如下:

转载于:https://www.cnblogs.com/zwdx/p/8409491.html

你可能感兴趣的文章
导航,头部,CSS基础
查看>>
[草稿]挂载新硬盘
查看>>
[USACO 2017 Feb Gold] Tutorial
查看>>
关于mysql中GROUP_CONCAT函数的使用
查看>>
OD使用教程20 - 调试篇20
查看>>
Java虚拟机(JVM)默认字符集详解
查看>>
Java Servlet 过滤器与 springmvc 拦截器的区别?
查看>>
(tmp >> 8) & 0xff;
查看>>
linux命令之ifconfig详细解释
查看>>
NAT地址转换
查看>>
Nhibernate 过长的字符串报错 dehydration property
查看>>
Deque - leetcode 【双端队列】
查看>>
gulp插件gulp-ruby-sass和livereload插件
查看>>
免费的大数据学习资料,这一份就足够
查看>>
clientWidth、clientHeight、offsetWidth、offsetHeight以及scrollWidth、scrollHeight
查看>>
企业级应用与互联网应用的区别
查看>>
itext jsp页面打印
查看>>
Perl正则表达式匹配
查看>>
DB Change
查看>>
nginx --rhel6.5
查看>>