Poi read and write the word template.

Source: Internet
Author: User
// There Is A Word Document Table // such as: // name $ {name} // call $ {Tel} // Replace the preceding variable import Java when reading records from the database. io. fileoutputstream; import Java. util. hashmap; import Java. util. iterator; import Java. util. list; import Java. util. map; import Java. util. map. entry; import Org. apache. poi. poixmldocument; import Org. apache. poi. xwpf. usermodel. xwpfdocument; import Org. apache. poi. xwpf. usermodel. xwpftable; import Org. apache. poi. xwpf. usermodel. xwpftablecell; import Org. apache. poi. xwpf. usermodel. xwpftablerow; public class docwriter {public static void searchandreplace (string srcpath, string destpath, Map <string, string> map) {try {xwpfdocument document = new xwpfdocument (poixmldocument. openpackage (srcpath); iterator it = document. gettablesiterator (); While (it. hasnext () {xwpftable table = (xwpftable) it. next (); int rcount = table. getnumberofrows (); For (INT I = 0; I <rcount; I ++) {xwpftablerow ROW = table. getrow (I); List <xwpftablecell> cells = row. gettablecells (); For (xwpftablecell cell: cells) {for (Entry <string, string> E: map. entryset () {If (cell. gettext (). equals (E. getkey () {Cell. removeparagraph (0); cell. settext (E. getvalue () ;}}}} fileoutputstream outstream = NULL; outstream = new fileoutputstream (destpath); document. write (outstream); outstream. close ();} catch (exception e) {e. printstacktrace () ;}} public static void main (string [] ARGs) throws exception {hashmap map = new hashmap (); map. put ("$ {name}", "Wang Wu"); map. put ("$ {Tel}", "8886666"); string srcpath = "C: \ 1.docx"; string destpath = "C: \ 2.doc"; searchandreplace (srcpath, destpath, MAP );}}

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.