Export Word Tools Class
Packageutil;Importjava.io.IOException;ImportJava.io.Writer;ImportJava.util.Map;ImportJavax.servlet.http.HttpServletResponse;ImportOrg.slf4j.Logger;Importorg.slf4j.LoggerFactory;Importfreemarker.template.Configuration;Importfreemarker.template.Template;Importfreemarker.template.TemplateException; Public classExportwordutil {Private Static FinalLogger log = Loggerfactory.getlogger (exportwordutil.class); /*** Export Word document *@paramResponse *@paramfilename Download file name *@paramModel Template Name *@paramDataMap Exporting Data*/ Public Static voidCreatedoc (httpservletresponse response, String fileName, string model, map<string,object>DataMap) {Response.setcontenttype ("Application/x-download;charset=utf-8"); Try{fileName=NewString (Filename.getbytes ("GBK"), "Iso-8859-1"); } Catch(Exception e) {log.error ("File name encoding Error!" "); } //Add a timestamp to the file nameFileName + = datetimeutils.getnowtimeshortstring () + ". Doc"; Response.AddHeader ("Content-disposition", "filename=" +filename+ "; Charset=utf-8"); //set the Modeled appliance method and path, which is specified by default in the/resources/exportword directoryConfiguration Configuration =NewConfiguration (); Configuration.setdefaultencoding ("UTF-8"); Configuration.setclassfortemplateloading (exportwordutil.class, "/resources/exportword"); Template Template=NULL; Try { //Loading TemplatesTemplate =configuration.gettemplate (model); Template.setencoding ("UTF-8"); } Catch(IOException e) {log.error ("Export Word loading template error!" "); E.printstacktrace (); } Writer out=NULL; Try { //output The object and encode the file nameout =Response.getwriter (); } Catch(IOException e) {log.error ("Export Word output stream creation Error!" "); E.printstacktrace (); } Try { //load and output data, generate Word documentstemplate.process (DataMap, out); } Catch(templateexception e) {e.printstacktrace (); Log.error ("Error exporting Word! "); } Catch(IOException e) {e.printstacktrace (); } }}
How to use in action:
/*** Export *@paramID *@paramResponse * @return */@RequestMapping ("/util/export.do") Public voidExport (httpservletresponse response) {Map<string, object> DataMap =NewHashmap<string, object>(); Datamap.put ("XM", "Little tabby cat");
Daamap.put ("Age", "3"); Exportwordutil.createdoc (Response,"Kitten Information", "XHMXX.FTL", DATAMAP); }
Java Export Word Direct download