Replace the contents of the Word/excel template document and download Java

Source: Internet
Author: User

ImportJava.io.BufferedInputStream;ImportJava.io.ByteArrayOutputStream;ImportJava.io.File;ImportJava.io.FileInputStream;Importjava.io.IOException;ImportJava.io.InputStream;ImportJava.io.OutputStream;ImportJava.util.Iterator;ImportJava.util.Map;Importjavax.servlet.http.HttpServletRequest;ImportJavax.servlet.http.HttpServletResponse;ImportOrg.apache.poi.hssf.usermodel.HSSFWorkbook;Importorg.apache.poi.hwpf.HWPFDocument;ImportOrg.apache.poi.hwpf.model.FieldsDocumentPart;ImportOrg.apache.poi.hwpf.usermodel.Field;ImportOrg.apache.poi.hwpf.usermodel.Fields;ImportOrg.apache.poi.hwpf.usermodel.Range;ImportOrg.apache.poi.ss.usermodel.Cell;ImportOrg.apache.poi.ss.usermodel.Row;ImportOrg.apache.poi.ss.usermodel.Sheet;ImportOrg.apache.poi.ss.usermodel.Workbook;ImportOrg.apache.poi.ss.usermodel.WorkbookFactory;

/** Case Template Download * **/ Public Static voidgeneratefile (httpservletrequest request,httpservletresponse response) {Map<string, string> map =fastmap.newinstance ();String calendaryear= Request.getparameter ("CalendarYear");Map.put ("201X", calendaryear); Content that needs to be replaced key is replaced byString Engfiletemplatename= "C:\Users\NUH-25\Desktop\ENG20160131.xlsx"; Template path replaced by String FileType= Engfiletemplatename.substring (Engfiletemplatename.lastindexof (".") + 1, Engfiletemplatename.length ()); if("xls". Equals (FileType) | | " xlsx. Equals (FileType)) Readwriteexcel (Request,response,map,engfiletemplatename); Else if("Doc". Equals (FileType) | | " Docx. Equals (FileType)) Readwriteword (Request,response,map,engfiletemplatename); } Public Static voidReadwriteword (HttpServletRequest request,httpservletresponse response,map<string, String>map,string engfiletemplatename) { FileInputStream in; Hwpfdocument HDT=NULL; Try{ in=NewFileInputStream (NewFile (engfiletemplatename)); HDT=Newhwpfdocument (in); } Catch(Exception E1) {e1.printstacktrace (); } Fields=Hdt.getfields (); Iterator<Field> it =Fields.getfields (Fieldsdocumentpart.main). iterator (); /*while (It.hasnext ()) {System.out.println (It.next (). GetType ()); } */ //Replace the specified field that reads the contents of the Word templateRange range =Hdt.getrange (); for(map.entry<string,string>Entry:map.entrySet ()) {Range.replacetext (Entry.getkey (), Entry.getvalue ()); } //output Word content file stream, provide downloadResponse.reset (); Response.setcontenttype ("Application/x-msdownload"); Response.setcharacterencoding ("GBK"); String FileType=Engfiletemplatename. SUBSTRING (Engfiletemplatename. LastIndexOf (".") + 1, engfiletemplatename. Length ()); String FileName= "" +system.currenttimemillis () + "." +FileType; Response.AddHeader ("Content-disposition", "attachment; Filename= "+fileName); Bytearrayoutputstream ostream=NewBytearrayoutputstream (); OutputStream Servletos=NULL; Try{Servletos=Response.getoutputstream (); Hdt.write (ostream); Servletos.write (Ostream.tobytearray ()); Servletos.flush (); Servletos.close (); } Catch(Exception e) {e.printstacktrace (); } } /*** * Case attachment Template Excel Modify download * *@paramRequest * *@paramResponse * *@throwsIOException*/ Public Static voidReadwriteexcel (HttpServletRequest request,httpservletresponse response,map<string, String>map,string engfiletemplatename) { Try {String FileType=Engfiletemplatename. SUBSTRING (Engfiletemplatename. LastIndexOf (".") + 1, engfiletemplatename. Length ()); FileInputStream in=NewFileInputStream (NewFile (engfiletemplatename));; InputStream InputStream=NewBufferedinputstream (in); Workbook Workbook=NULL; if(Filetype.equals ("xls") ) {Workbook=NewHssfworkbook (InputStream); } Else if(Filetype.equals ("xlsx")) { //workbook = new Xssfworkbook (inputstream);Workbook =workbookfactory.create (InputStream); } Else{System.out.println ("The Excel format you entered is incorrect"); } Iterator<Sheet> iterator =Workbook.sheetiterator (); while(Iterator.hasnext ()) {Sheet Sheet=Iterator.next (); for(Row row:sheet) { for(Cell cell:row) {if(1==Cell.getcelltype ()) {String cellstring=Cell.getstringcellvalue (); for(map.entry<string,string>Entry:map.entrySet ()) { if(Cellstring.contains (Entry.getkey ())) {String newstring=Cellstring.replace (Entry.getkey (), Entry.getvalue ()); Cell.setcellvalue (newstring); } } } } } } //output Excel content file stream, available for downloadResponse.reset (); Response.setcontenttype ("Application/x-msdownload"); Response.setcharacterencoding ("GBK"); String FileName= "" +system.currenttimemillis () + "." +FileType; Response.AddHeader ("Content-disposition", "attachment; Filename= "+fileName); Bytearrayoutputstream ostream=NewBytearrayoutputstream (); OutputStream Servletos=NULL; Try{Servletos=Response.getoutputstream (); Workbook.write (ostream); Servletos.write (Ostream.tobytearray ()); Servletos.flush (); Servletos.close (); } Catch(Exception e) {e.printstacktrace (); } } Catch(Exception e) {e.printstacktrace (); Debug.logerror (E, module); } }

Replace the contents of the Word/excel template document and download Java

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.