java POI往word文檔中指定位置插入表格,javapoi

來源:互聯網
上載者:User

java POI往word文檔中指定位置插入表格,javapoi

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<XWPFParagraph> paragraphList = doc.getParagraphs(); if (paragraphList != null && paragraphList.size() > 0) { for (XWPFParagraph paragraph : paragraphList) { List<XWPFRun> runs = paragraph.getRuns(); for (int i = 0; i < runs.size(); i++) { String text = runs.get(i).getText(0); 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<DTO> 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 

<dependency>            <groupId>org.apache.poi</groupId>            <artifactId>poi-excelant</artifactId>            <version>3.12</version>        </dependency>        <dependency>            <groupId>org.apache.poi</groupId>            <artifactId>poi-scratchpad</artifactId>            <version>3.12</version>        </dependency>        <dependency>            <groupId>org.apache.poi</groupId>            <artifactId>poi-ooxml</artifactId>            <version>3.8</version>        </dependency>        <dependency>            <groupId>org.apache.poi</groupId>            <artifactId>poi-ooxml-schemas</artifactId>            <version>3.8</version>        </dependency><!-- 產生圖片-->  <dependency>        <groupId>org.jfree</groupId>        <artifactId>jfreechart</artifactId>        <version>1.0.19</version>    </dependency>    <dependency><!--支援插入圖片-->        <groupId>org.docx4j</groupId>        <artifactId>docx4j</artifactId>        <version>3.3.1</version>    </dependency>

 

在文檔中指定位置  設定好  關鍵字如  demo 中的 “$key”

結果圖如下:

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.