POI generates Word documents and poiword documents

Source: Internet
Author: User

POI generates Word documents and poiword documents

 

POI generates Word documents

POI is an excellent open-source library for processing office documents in Java, among which Excel is the most well handled and the documents are also detailed. However, many netizens think that it is inferior in Word document processing, but I still chose POI for generating this completed document.

You need to complete the function configuration word Template

Use $ {xx} to configure tags. If the table is configured with a table name in a column of the corresponding row

Note:In word documents, if two similar character styles are different, word is stored in differentRUNElement, so many friends need to save it as a separate file after configuration, and then do not merge the tags that are not together into oneRUNElement, if the file is relatively large, I believe this is definitely a relatively painful thing, here we will focus on this problem. My solution is to keep the firstRUNTo delete other styles.

Parse word template

First, you need to convert the fileXWPFDocumentObject.opcpackage, But if you useopcpackageOpen method: The opened file and the final generated file cannot be the same file. Here I use the file stream method.

public XWPFDocument openDocument() {        XWPFDocument xdoc = null;        InputStream is = null;        try {            is = new FileInputStream(saveFile);            xdoc = new XWPFDocument(is);        } catch (IOException e) {            e.printStackTrace();        }        return xdoc;    }

How to obtain non-list tagsXWPFDocumentThe object contains all paragraphs and tables. Currently, the nested table is not considered.p.getText()Obtain the document configuration information in the section as follows:

// Obtain the public List of all texts in the section set <TagInfo> getWordTag (XWPFDocument doc, String regex) {List <TagInfo> tags = new ArrayList <TagInfo> (); // List of common paragraphs <XWPFParagraph> pars = doc. getParagraphs (); for (int I = 0; I <pars. size (); I ++) {XWPFParagraph p = pars. get (I); setTagInfoList (tags, p, regex);} // List of paragraphs in Table <XWPFTable> commTables = getDocTables (doc, false, regex); for (XWPFTable table: commTables) {List <XWPFParagraph> tparags = getTableParagraph (table); for (int I = 0; I <tparags. size (); I ++) {XWPFParagraph p = tparags. get (I); setTagInfoList (tags, p, regex) ;}} return tags ;}

After obtaining the text, use regular expression parsing and save it to TagInfo.

// Add the parsed section information private void setTagInfoList (List <TagInfo> list, XWPFParagraph p, String regex) to the taglist {if (regex = ") regex = defaultRegex; pattern pattern = Pattern. compile (regex); Matcher matcher = pattern. matcher (p. getText (); int startPosition = 0; while (matcher. find (startPosition) {String match = matcher. group (); if (! List. contains (new TagInfo (match, match, "") {list. add (new TagInfo (match, match, "");} startPosition = matcher. end ();}}

Parse table

// Obtain the configuration information public Map <String, List <TagInfo> getTableTag (XWPFDocument doc, String regex) {Map <String, list <TagInfo> mapList = new HashMap <String, List <TagInfo> (); List <XWPFTable> lstTables = getDocTables (doc, true, regex); for (XWPFTable table: lstTables) {// obtain the first cell of each table and the last row String strTableName = getTableListName (table, regex ); list <TagInfo> list = new Array List <TagInfo> (); List <TagInfo> lstTag = new ArrayList <TagInfo> (); int rowSize = table. getRows (). size (); XWPFTableRow lastRow = table. getRow (rowSize-1); for (XWPFTableCell cell: lastRow. getTableCells () {for (XWPFParagraph p: cell. getParagraphs () {// remove the blank string if (p. getText ()! = Null & p. getText (). length ()> 0) {setTagInfoList (lstTag, p, regex) ;}} list. add (lstTag); // add to dataset mapList. put (strTableName, list);} return mapList ;}
Generate WORD Documents

Difficult to replace tags
The input data format includes three formtags and one tableTag.

{"formTags":
[{"TagName":"${xxxx}","TagText":"${xxxx}","TagValue":""},
{"TagName":"${123}","TagText":"${123}","TagValue":""},
{"TagName":"${ddd}","TagText":"${ddd}","TagValue":""}],
"tableTags":{
"${table}":[
[{"TagName":"${COL1}","TagText":"${COL1}","TagValue":""},{"TagName":"${COL2}","TagText":"${COL2}","TagValue":""}]
]}
}

Common documents are generated and the configuration style is retained.POIProvides the searchText method to return allRUNTag, Which is compared by a character. If the first matched text is counted, all tags of the type $ {xxx} under the current condition cannot be replaced.
Replace common text tags

Public void ReplaceInParagraph (List <TagInfo> tagList, XWPFParagraph para, String regex) {if (regex = "") regex = defaultRegex; List <XWPFRun> runs = para. getRuns (); for (TagInfo ti: tagList) {String find = ti. tagText; String replValue = ti. tagValue; TextSegement found = para. searchText (find, new PositionInParagraph (); if (found! = Null) {// determines whether the search content is in the same Run label if (found. getBeginRun () = found. getEndRun () {XWPFRun run = runs. get (found. getBeginRun (); String runText = run. getText (run. getTextPosition (); String replaced = runText. replace (find, replValue); run. setText (replaced, 0);} else {// There are multiple Run tags StringBuilder sb = new StringBuilder (); for (int runPos = found. getBeginRun (); runPos <= found. getEndRun (); runPos ++) {XWPFRun run = runs. get (runPos); sb. append (run. getText (run. getTextPosition ();} String connectedRuns = sb. toString (); String replaced = connectedRuns. replace (find, replValue); XWPFRun firstRun = runs. get (found. getBeginRun (); firstRun. setText (replaced, 0); // Delete the run label for (int runPos = found. getBeginRun () + 1; runPos <= found. getEndRun (); runPos ++) {// clear other TAG content XWPFRun partNext = runs. get (runPos); partNext. setText ("", 0) ;}}// check whether the label in the section has been replaced by Pattern pattern = Pattern. compile (regex); Matcher matcher = pattern. matcher (para. getText (); boolean find = matcher. find (); if (find) {ReplaceInParagraph (tagList, para, regex); find = false ;}}

The table mainly copies the template row and then modifies the content in the template row.
Copy text labelsRUN

Private void CopyRun (XWPFRun target, XWPFRun source) {target. getCTR (). setRPr (source. getCTR (). getRPr (); // sets the text target. setText (source. text ());}

Copy paragraphXWPFParagraph

Private void copyParagraph (XWPFParagraph target, XWPFParagraph source) {// set the paragraph style target. getCTP (). setPPr (source. getCTP (). getPPr (); // Add the Run tag for (int pos = 0; pos <target. getRuns (). size (); pos ++) {target. removeRun (pos);} for (XWPFRun s: source. getRuns () {XWPFRun targetrun = target. createRun (); CopyRun (targetrun, s );}}

Copy CellsXWPFTableCell

Private void copyTableCell (XWPFTableCell target, XWPFTableCell source) {// column attribute target. getCTTc (). setTcPr (source. getCTTc (). getTcPr (); // Delete All target targetCell cells for (int pos = 0; pos <target. getParagraphs (). size (); pos ++) {target. removeParagraph (pos);} // Add a section for (XWPFParagraph sp: source. getParagraphs () {XWPFParagraph targetP = target. addParagraph (); copyParagraph (targetP, sp );}}

Copy rowXWPFTableRow

Private void CopytTableRow (XWPFTableRow target, XWPFTableRow source) {// copy the style target. getCtRow (). setTrPr (source. getCtRow (). getTrPr (); // copy the cell for (int I = 0; I <target. getTableCells (). size (); I ++) {copyTableCell (target. getCell (I), source. getCell (I ));}}

Copyright. For more information, see the source.Yang hanbo
All the above functions are completed. As long as you configure the specifications, You can output the template content completely as it is. Thank you for your support.
Second, the java code is really speechless. There are various Chinese garbled characters in get or post.

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.