Java POI inserts a table at a specified position in the Word document, javapoi

Source: Internet
Author: User

Java POI inserts a table at a specified position in the Word document, 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.docx 4j. traversalUtil; import org.docx 4j. dml. wordprocessingDrawing. inline; import org.docx 4j. finders. rangeFinder; import org.docx 4j. openpackaging. packages. wordprocessingMLPackage; import org.docx 4j. openpackaging. parts. wordprocessingML. binaryPartAbstractImage; import org.docx 4j. openpackaging. parts. wordprocessingML. mainDocumentPart; import org.docx 4j. wml. body; import org.docx 4j. wml. CTBookmark; import org.docx 4j. wml. document; import org.docx 4j. wml. drawing; import org.docx 4j. wml. objectFactory; import org.docx 4j. wml. p; import org.docx 4j. 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"; // name of the bookmark reporting Image Location public void exportBg (OutputStream out) {String srcPath = "D: /tp/fx.docx "; String targetPath =" D:/tp/fx2.docx "; String key =" $ key "; // In the document, replace the insert table location XWPFDocument doc = null; File targetFile = null; try {doc = new XWPFDocument (POIXMLDocument. openPackage (srcPath); List <XWPFParagraph> paragraphLis T = 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 (); // INSERT table XWPFTable table = doc at the specified cursor position. 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) ;}}/*** insert information into the table * @ param data */private void inserInfo (XWPFTable table) {List <DTO> data = mapper. getInfo (); // The data to be inserted. XWPFTableRow row = table. getRow (0); XWPFTableCell cell = null; for (int col = 1; col <6; col ++) {// a column is created by default, that is, the number of columns created from Column 2nd // The first row. The column CTTcPr = row is automatically added to the subsequent rows. createCell (). get CTTc (). addNewTcPr (); CTTblWidth width = cPr. addNewTcW (); if (col = 1 | col = 2 | col = 4) {width. setW (BigInteger. valueOf (2000);} row. getCell (0 ). setText ("indicator"); row. getCell (1 ). setText ("Metric description"); row. getCell (2 ). setText ("formula"); row. getCell (3 ). setText ("reference value"); row. getCell (4 ). setText ("Description"); row. getCell (5 ). setText ("calculated value"); for (DTO item: data) {row = table. createRow (); row. getCell (0 ). setText (item. getZbmc (); ce Ll = 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? "Unable to calculate": item. getJsjg ());}}}

2. Controller

Public void exportBg (HttpServletResponse response) {try {response. setContentType ("application/octet-stream"); String name = "report"; 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> <groupId> org. apache. poi </groupId> <artifactId> poi-scratchpad </artifactId> <version> 3.12 </version> </dependency> <groupId> org. apache. poi </groupId> <artifactId> poi-ooxml </artifactId> <version> 3.8 </version> </dependency> <groupId> org. apache. p Oi </groupId> <artifactId> poi-ooxml-schemas </artifactId> <version> 3.8 </version> </dependency> <! -- Generate an image --> <dependency> <groupId> org. jfree </groupId> <artifactId> jfreechart </artifactId> <version> 1.0.19 </version> </dependency> <! -- Images can be inserted --> <groupId> org.docx 4j </groupId> <artifactId> docx4j </artifactId> <version> 3.3.1 </version> </dependency>

 

Set the keyword at the specified position in the document, for example, "$ key" in the demo"

The result is as follows:

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.