今天很荣幸又破解一现实难题:自动生成并导出word文档
先看页面效果:
word效果:
代码:
- 先搭建struts2项目
- 创建action,并在struts.xml完成注册
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN" "http://struts.apache.org/dtds/struts-2.3.dtd"> <struts> <!--Overwrite Convention --> <constant name="struts.configuration.xml.reload"value="true"/> <constant name="struts.devMode"value="false"/> <constant name="struts.ui.theme"value="simple"/> <constant name="struts.i18n.encoding"value="UTF-8" /> <constant name="struts.ognl.allowStaticMethodAccess"value="true"/> <constant name="struts.multipart.maxSize"value="20971520" /> <package name="SK"extends="struts-default"namespace="/"> <action name="user!*"class="qh.sk.action.UserAction"method="{1}"> <result name="{1}">/WEB-INF/user-{1}.jsp</result> <result name="exportFile"type="stream"> <param name="contentType">application/octet-stream</param> <param name="inputName">inputStream</param> <param name="contentDisposition">attachment;filename="${fileName}"</param> <param name="bufferSize">4096</param> </result> </action> </package> </struts>
UserAction部分:
packageqh.sk.action; importjava.awt.Color; importjava.io.File; importjava.io.FileOutputStream; importjava.io.IOException; importjava.io.InputStream; importjava.io.UnsupportedEncodingException; importjava.util.HashMap; importjava.util.List; importjava.util.UUID; importorg.apache.struts2.ServletActionContext; importorg.framework.util.DateUtil; importorg.framework.util.FileUtil; importcom.lowagie.text.BadElementException; importcom.lowagie.text.Cell; importcom.lowagie.text.Document; importcom.lowagie.text.DocumentException; importcom.lowagie.text.Element; importcom.lowagie.text.Font; importcom.lowagie.text.PageSize; importcom.lowagie.text.Paragraph; importcom.lowagie.text.Table; importcom.lowagie.text.pdf.BaseFont; importcom.lowagie.text.rtf.RtfWriter2; importcom.lowagie.text.rtf.style.RtfFont; importcom.opensymphony.xwork2.ActionSupport; @SuppressWarnings("serial") public class UserAction extendsActionSupport{ privateString fileName; privateInputStream inputStream; publicString getFileName() { try{ String filename = new String(this.fileName.getBytes("GBK"),"ISO8859-1"); returnfilename; } catch(UnsupportedEncodingException e) { e.printStackTrace(); return "code"; } } public voidsetFileName(String fileName) { this.fileName =fileName; } publicInputStream getInputStream() { returninputStream; } public voidsetInputStream(InputStream inputStream) { this.inputStream =inputStream; } public String test() throwsDocumentException, IOException{ String tempFolder = ServletActionContext.getServletContext().getRealPath("/temp/"+UUID.randomUUID()); FileUtil.newFolder(tempFolder); String doc_outlearn=tempFolder+"/temp.doc"; File file =null; try{ file = newFile(doc_outlearn); Document document = new Document(PageSize.A4, 50, 50, 50, 50); RtfWriter2.getInstance(document, newFileOutputStream(file)); document.open(); exportWords(document); document.close(); this.setFileName("SK1995.doc"); this.inputStream =newjava.io.FileInputStream(doc_outlearn); } catch(Exception e) { //TODO Auto-generated catch block e.printStackTrace(); } finally{ file.deleteOnExit(); } return "exportFile"; } public void exportWords(Document document) throwsDocumentException, IOException{ //设置中文字体 float sureWidths[]={8f,8f,8f,8f,8f,8f,10f,10f,8f,8f,8f,8f}; document.setMargins(50f, 50f, 50f, 50f); RtfFont headFont = new RtfFont("华文细黑", 24, Font.BOLD, Color.BLACK); Paragraph title= new Paragraph(" SK个人项目 申 请 书 ",headFont); title.setAlignment(Element.ALIGN_CENTER); RtfFont titleFont = new RtfFont("华文细黑", 16, Font.BOLD, Color.BLACK); document.add(title); Table firstTable = new Table(2); float firstWidths[]={30f,70f}; firstTable.setWidths(firstWidths); firstTable.setWidth(90); firstTable.setBorder(0); firstTable.setBorderWidth(0); firstTable.addCell(fillCellWithNoBorder("项目名称:",titleFont,Element.ALIGN_RIGHT,10,0,0)); firstTable.addCell(fillCellWithBottomBorder("SK",titleFont,Element.ALIGN_LEFT,10,0,0)); firstTable.addCell(fillCellWithNoBorder("项目负责人:",titleFont,Element.ALIGN_RIGHT,10,0,0)); firstTable.addCell(fillCellWithBottomBorder("SK1995",titleFont,Element.ALIGN_LEFT,10,0,0)); document.add(firstTable); Paragraph _paragraph=setParagraphStyle(titleFont,0f,20f,0f,Paragraph.ALIGN_CENTER,8); _paragraph.add(" "+DateUtil.getNow("yyyy 年 MM 月 dd")); document.add(_paragraph); document.newPage(); RtfFont contextFont = new RtfFont("华文仿 宋 _GB2312", 12, Font.NORMAL, Color.BLACK); RtfFont contextBoldFont = new RtfFont("华文仿 宋 _GB2312", 12, Font.BOLD, Color.BLACK); Table xmTable = new Table(12); xmTable.setWidths(sureWidths); xmTable.setWidth(100); xmTable.setAlignment(Table.ALIGN_CENTER); xmTable.addCell(fillCell("姓名",contextBoldFont,Element.ALIGN_CENTER,3,6)); xmTable.addCell(fillCell("SK1995",contextFont,Element.ALIGN_CENTER,3,6)); xmTable.addCell(fillCell("年龄",contextBoldFont,Element.ALIGN_CENTER,3,6)); xmTable.addCell(fillCell("1995",contextFont,Element.ALIGN_CENTER,3,6)); document.add(xmTable); } public Cell fillCellWithNoBorder(String value, RtfFont contextFont,int align,int spacing,int colspans,int rowspan) throwsBadElementException { Cell cell=newCell(); cell.setHorizontalAlignment(align); cell.setVerticalAlignment(Element.ALIGN_MIDDLE); cell.setBorderWidth(0); if (colspans>0) { cell.setColspan(colspans); } if (rowspan>0) { cell.setRowspan(rowspan); } Paragraph label= newParagraph(value, contextFont); label.setSpacingBefore(spacing); label.setSpacingAfter(spacing); cell.addElement(label); returncell; } public Cell fillCellWithBottomBorder(String value, RtfFont contextFont,int align,int spacing,int colspans,int rowspan) throwsBadElementException { Cell cell=newCell(); cell.setHorizontalAlignment(align); cell.setVerticalAlignment(Element.ALIGN_MIDDLE); cell.setBorderWidthTop(0); cell.setBorderWidthLeft(0); cell.setBorderWidthRight(0); cell.setBorderWidthBottom(1); if (colspans>0) { cell.setColspan(colspans); } if (rowspan>0) { cell.setRowspan(rowspan); } Paragraph label= newParagraph(value, contextFont); label.setSpacingBefore(spacing); label.setSpacingAfter(spacing); cell.addElement(label); returncell; } public Cell fillCell(String value, RtfFont contextFont,int align,int spacing,int colspans) throwsBadElementException { Cell cell=newCell(); cell.setHorizontalAlignment(align); cell.setVerticalAlignment(Element.ALIGN_MIDDLE); if (colspans>0) { cell.setColspan(colspans); } Paragraph label= newParagraph(value, contextFont); label.setSpacingBefore(spacing); label.setSpacingAfter(spacing); cell.addElement(label); returncell; } public Cell fillCell(String value, RtfFont contextFont,int align,int spacing,int colspans,int rowspan) throwsBadElementException { Cell cell=newCell(); cell.setHorizontalAlignment(align); cell.setVerticalAlignment(Element.ALIGN_MIDDLE); if (colspans>0) { cell.setColspan(colspans); } if (rowspan>0) { cell.setRowspan(rowspan); } Paragraph label= newParagraph(value, contextFont); label.setSpacingBefore(spacing); label.setSpacingAfter(spacing); cell.addElement(label); returncell; } public Paragraph setParagraphStyle(Font font , float firstLineIndent , float leading , float indentationRight , int alignment, intspacing) { Paragraph _paragraph = newParagraph(); _paragraph.setFont(font); _paragraph.setFirstLineIndent(firstLineIndent); _paragraph.setLeading(leading); _paragraph.setIndentationRight(indentationRight); _paragraph.setAlignment(alignment); _paragraph.setSpacingBefore(spacing); _paragraph.setSpacingAfter(spacing); return_paragraph; } }
启动tomcat,http://localhost:8080/test/user!test
完成!