Java fills in template tables and dynamically generated tables

Source: Internet
Author: User
Tags getcolor


The effect sees and then looks at the code, the code in the method all has the comment to say the nonsense no more:

"'
Package com.poi;

Import Java.io.FileInputStream;
Import Java.io.FileOutputStream;
Import java.io.IOException;
Import Java.io.InputStream;
Import Java.io.OutputStream;
Import java.util.ArrayList;
Import Java.util.HashMap;
Import Java.util.Iterator;
Import java.util.List;
Import Java.util.Map;
Import Java.util.regex.Matcher;
Import Java.util.regex.Pattern;

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.openxmlformats.schemas.wordprocessingml.x2006.main.CTFonts;
Import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTInd;
Import Org.openxmlformats.schemas.wordprocessingml.x2006.main.CTP;
Import Org.openxmlformats.schemas.wordprocessingml.x2006.main.CTPPr;
Import Org.openxmlformats.schemas.wordprocessingml.x2006.main.CTRPr;
Import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTSpacing;
Import Org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTc;
Import Org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTcPr;

public class Generaltemplatedocx {

/** * @param args */public static void main (string[] args) {//TODO auto-generated method stub String FilePath = "C    :/users/administrator/desktop/doc/template. docx ";    String outFile = "c:/users/administrator/desktop/generate template. docx";    map<string, object> params = new hashmap<string, object> ();    Params.put ("myTable", "my Form");    Params.put ("name", "small treasure");    Params.put ("Age", "XX");    Params.put ("Sex", "male");    Params.put ("Job", "Meat shield");    Params.put ("hobby", "e-commerce");    Params.put ("Phone", "1717");        try {generaltemplatedocx GT = new Generaltemplatedocx ();        Gt.templatewrite (FilePath, OutFile, params, Gt.generatetestdata (10));    System.out.println ("Generate template Success");        } catch (Exception e) {//TODO auto-generated catch block System.out.println ("Generate template Failed");    E.printstacktrace (); }}/** * Use a docx document as a template, then replace the contents of it, and then write to the target document. * * @throws Exception */public void Templatewrite (String filePath, String outFile, map<string, object> param S,liSt<list<string>> resultlist) throws Exception {InputStream is = new FileInputStream (FilePath);    Xwpfdocument doc = new Xwpfdocument (IS);    Replace the variable This.replaceinpara (doc, params) inside the paragraph;    Replace the variables inside the table and insert the data this.insertvaluetotable (Doc, params,resultlist);    OutputStream OS = new FileOutputStream (outFile);    Doc.write (OS);    This.close (OS); This.close (IS);} /** * Replace the variable inside the paragraph * * @param doc * to replace the document * @param params * parameter */private void Replaceinpara (xwpfdocum    ent doc, map<string, object> params) {iterator<xwpfparagraph> Iterator = Doc.getparagraphsiterator ();    Xwpfparagraph para;        while (Iterator.hasnext ()) {para = Iterator.next ();    This.replaceinpara (para, params); }}/** * Replace the variable inside the paragraph * * @param para * The paragraph to be replaced * @param params * parameter */private boolean Replaceinpara (XWP    Fparagraph para, map<string, object> params) {Boolean data = false;    List<xwpfrun> runs; Matcher MATcher;        if (This.matcher (Para.getparagraphtext ()). Find ()) {runs = Para.getruns ();            for (int i = 0; i < runs.size (); i++) {Xwpfrun run = runs.get (i);            String Runtext = run.tostring ();            Matcher = This.matcher (Runtext); if (Matcher.find ()) {while (Matcher = This.matcher (Runtext)). Find ()) {runtext = match                Er.replacefirst (string.valueof (params. Get (Matcher.group (1))); }//Directly call Xwpfrun's SetText () method to set the text, the underlying will recreate a xwpfrun, append the text behind the current text,//So we can not directly set the value, we need to delete the current run, and then                Then manually insert a new run yourself.                Para.removerun (i);            Para.insertnewrun (i). SetText (Runtext);        }}} and Else if (This.matcherrow (Para.getparagraphtext ())) {runs = Para.getruns ();        System.out.println ("Run" + runs);    data = true; } return data; /** * Fills data by template row style, and does not implement special style fills (such as column merging), only for normal styles (such as paragraph spacing indent font alignment) * * @param DOC * Document to be replaced * @param params * parameter * @param resultlist * data to be traversed * @throws Exception */priv ate void Insertvaluetotable (Xwpfdocument doc, map<string, object> params,list<list<string>>    Resultlist) throws Exception {iterator<xwpftable> Iterator = Doc.gettablesiterator ();    xwpftable table = null;    list<xwpftablerow> rows = null;    List<xwpftablecell> cells = null;    List<xwpfparagraph> paras; list<xwpftablecell> tmpcells = null;//template column Xwpftablerow Tmprow = null;//match with Xwpftablecell TmpCell = null;//Horse    With Boolean flag = false;//whether the table int thisrow=0 is found;        while (Iterator.hasnext ()) {table = Iterator.next ();        rows = Table.getrows ();            for (int i = 1; I <= rows.size (); i++) {cells = Rows.get (i-1). Gettablecells ();                for (Xwpftablecell cell:cells) {paras = cell.getparagraphs ();  for (Xwpfparagraph Para:paras) {                  if (This.replaceinpara (para, params)) {System.out.println ("this.row=" + i);                        thisrow=i;//Find template Line Tmprow = Rows.get (i-1);                        Cells = Tmprow.gettablecells ();                                System.out.println ("cells.size () =" + cells.size () + "Resultlist.get (0). Size () ="                        + resultlist.get (0). Size ());                            if (cells.size () = = Resultlist.get (0). Size ()) {flag = true;                        Break        }}}}}} if (!flag) {System.out.println ("Table not Found");    Return    } tmpcells = Tmprow.gettablecells ();        for (int i = 0, Len = resultlist.size (), i < Len; i++) {System.out.println ("start writing" + i + "line");        Xwpftablerow row = Table.createrow ();  Row.setheight (Tmprow.getheight ());      list<string> list = Resultlist.get (i);        Cells = Row.gettablecells (); The inserted rows fill the same number of columns as the first row of the table for (int k = 0, Klen = Cells.size (); k < Klen; k++) {Tmpcell = Tmpcells.get (k)            ;            Xwpftablecell cell = Cells.get (k);        Setcelltext (Tmpcell, Cell, List.get (k)); }//Continue to write the remaining columns for (int j = cells.size (), Jlen = List.size (); J < Jlen; J + +) {Tmpcell = Tmpcell            S.get (j);            Xwpftablecell cell = Row.addnewtablecell ();            Setcelltext (Tmpcell, Cell, List.get (j));        System.out.println ("Content" + List.get (j)); }}//delete template line Table.removerow (thisRow-1);} public void Setcelltext (Xwpftablecell Tmpcell, Xwpftablecell cell, String text) throws Exception {CTTc cttc2 =    TMPCELL.GETCTTC ();    CTTCPR ctPr2 = CTTC2.GETTCPR ();    CTTc CTTc = CELL.GETCTTC ();    CTTCPR CTPR = CTTC.ADDNEWTCPR ();    Cell.setcolor (Tmpcell.getcolor ()); Cell.setverticalalignment (Tmpcell.getvertIcalalignment ());    if (CTPR2.GETTCW () = null) {CTPR.ADDNEWTCW (). SETW (CTPR2.GETTCW (). GETW ());    } if (ctpr2.getvalign () = null) {ctpr.addnewvalign (). Setval (Ctpr2.getvalign (). Getval ());        } if (Cttc2.getplist (). Size () > 0) {CTP CTP = Cttc2.getplist (). get (0); if (CTP.GETPPR () = null) {if (CTP.GETPPR (). GETJC () = null) {cttc.getplist (). Get (0). addnewppr            (). ADDNEWJC (). Setval (CTP.GETPPR (). GETJC (). Getval ());    }}} if (ctpr2.gettcborders () = null) {ctpr.settcborders (Ctpr2.gettcborders ());    } xwpfparagraph tmpp = Tmpcell.getparagraphs (). get (0);    Xwpfparagraph CELLP = cell.getparagraphs (). get (0);    Xwpfrun TMPR = null;    if (tmpp.getruns () = null && tmpp.getruns (). Size () > 0) {tmpr = Tmpp.getruns (). get (0);    } Xwpfrun Cellr = Cellp.createrun ();    Cellr.settext (text); Copy font information if (TMPR! = null) {Cellr.setbold (tmpr.isbold());        Cellr.setitalic (Tmpr.isitalic ());        Cellr.setstrike (Tmpr.isstrike ());        Cellr.setunderline (Tmpr.getunderline ());        Cellr.setcolor (Tmpr.getcolor ());        Cellr.settextposition (Tmpr.gettextposition ());        if (tmpr.getfontsize ()! =-1) {cellr.setfontsize (Tmpr.getfontsize ());        } if (tmpr.getfontfamily () = null) {cellr.setfontfamily (tmpr.getfontfamily ()); if (tmpr.getctr () = null) {if (Tmpr.getctr (). ISSETRPR ()) {CTRPR TMPRPR = tmpr.getctr                (). GETRPR ();                    if (tmprpr.issetrfonts ()) {ctfonts tmpfonts = tmprpr.getrfonts (); CTRPR CELLRPR = cellr.getctr (). ISSETRPR ()?                    Cellr. GETCTR (). GETRPR (): Cellr.getctr (). ADDNEWRPR (); Ctfonts cellfonts = cellrpr.issetrfonts ()?                    Cellrpr. Getrfonts (): Cellrpr.addnewrfonts (); Cellfonts.setascii (Tmpfonts.getaScii ());                    Cellfonts.setasciitheme (Tmpfonts.getasciitheme ());                    Cellfonts.setcs (Tmpfonts.getcs ());                    Cellfonts.setcstheme (Tmpfonts.getcstheme ());                    Cellfonts.seteastasia (Tmpfonts.geteastasia ());                    Cellfonts.seteastasiatheme (Tmpfonts.geteastasiatheme ());                    Cellfonts.sethansi (Tmpfonts.gethansi ());                Cellfonts.sethansitheme (Tmpfonts.gethansitheme ());    }}}}//Copy paragraph information cellp.setalignment (Tmpp.getalignment ());    Cellp.setverticalalignment (Tmpp.getverticalalignment ());    Cellp.setborderbetween (Tmpp.getborderbetween ());    Cellp.setborderbottom (Tmpp.getborderbottom ());    Cellp.setborderleft (Tmpp.getborderleft ());    Cellp.setborderright (Tmpp.getborderright ());    Cellp.setbordertop (Tmpp.getbordertop ());    Cellp.setpagebreak (Tmpp.ispagebreak ());           if (TMPP.GETCTP () = null) {if (TMPP.GETCTP (). GETPPR () = null) { CTPPR tmpppr = TMPP.GETCTP (). GETPPR (); CTPPR cellppr = CELLP.GETCTP (). GETPPR ()! = null?            CELLP. GETCTP (). GETPPR (): CELLP.GETCTP (). ADDNEWPPR ();            Copy Paragraph spacing information ctspacing tmpspacing = tmpppr.getspacing ();                        if (tmpspacing! = null) {ctspacing cellspacing = cellppr.getspacing ()! = null? cellppr                . getspacing (): cellppr.addnewspacing ();                if (tmpspacing.getafter () = null) {Cellspacing.setafter (Tmpspacing.getafter ()); } if (tmpspacing.getafterautospacing () = null) {cellspacing.setafterautospacing (Tmpspa                Cing. getafterautospacing ()); } if (tmpspacing.getafterlines () = null) {Cellspacing.setafterlines (tmpspacing.getafte                Rlines ()); } if (Tmpspacing.getbefore () = null) {Cellspacing.setbefore(Tmpspacing.getbefore ()); } if (tmpspacing.getbeforeautospacing () = null) {cellspacing.setbeforeautospacing (tmps                Pacing. getbeforeautospacing ()); } if (tmpspacing.getbeforelines () = null) {Cellspacing.setbeforelines (tmpspacing.getbe                Forelines ());                } if (tmpspacing.getline () = null) {Cellspacing.setline (Tmpspacing.getline ()); } if (tmpspacing.getlinerule () = null) {Cellspacing.setlinerule (tmpspacing.ge                Tlinerule ());            }}//Copy paragraph indent information ctind Tmpind = Tmpppr.getind (); if (tmpind! = null) {Ctind cellind = Cellppr.getind ()! = null? Cellppr.getind ():                Cellppr.addnewind (); if (tmpind.getfirstline () = null) {Cellind.setfirstline (Tmpind.getfiRstline ()); } if (tmpind.getfirstlinechars () = null) {Cellind.setfirstlinechars (Tmpind.getfirstlin                Echars ());                } if (tmpind.gethanging () = null) {cellind.sethanging (tmpind.gethanging ()); } if (tmpind.gethangingchars () = null) {Cellind.sethangingchars (tmpind.gethangin                Gchars ());                } if (tmpind.getleft () = null) {Cellind.setleft (Tmpind.getleft ());                } if (tmpind.getleftchars () = null) {Cellind.setleftchars (Tmpind.getleftchars ());                } if (tmpind.getright () = null) {Cellind.setright (Tmpind.getright ()); } if (tmpind.getrightchars () = null) {Cellind.setrightchars (Tmpind.getrigh                TCHARs ()); }}}}}/** * Regular Match String * *@param str * @return */private Matcher Matcher (String str) {Pattern pattern = Pattern.compile ("\\$\\{(. +?)    \ \} ", pattern.case_insensitive);    Matcher Matcher = Pattern.matcher (str); return matcher;} /** * Regular Match String * * @param str * @return */private boolean matcherrow (String str) {Pattern pattern = pattern.compile ("\ \$\\[(.+?)    \ \] ", pattern.case_insensitive);    Matcher Matcher = Pattern.matcher (str); return Matcher.find ();}         /** * Close Input stream * * @param is */private void Close (InputStream are) {if (is = null) {try {is.close ();        } catch (IOException e) {e.printstacktrace (); }}}/** * Closes the output stream * * @param os */private void Close (OutputStream os) {if (OS! = null) {try {os.        Close ();        } catch (IOException e) {e.printstacktrace (); }}}//generate test Data public list<list<string>> generatetestdata (int num) {list<list<string>> result List = new ArraylisT<list<string>> ();        for (int i = 1; I <= num; i++) {list<string> List = new arraylist<string> ();        List.add ("" + i);        List.add ("Test _" + i);        List.add ("Test 2_" + i);        List.add ("Test 3_" + i);        List.add ("Test 4_" + i);        List.add ("Test 5_" + i);    Resultlist.add (list); } return resultlist;}

}

"' This code is not processed on the paragraph text, it needs to add its own set method.

Java fills in template tables and dynamically generated tables

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.