今天很荣幸又破解一现实难题:自动生成并导出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部分:
package qh.sk.action; import java.awt.Color;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.List;
import java.util.UUID; import org.apache.struts2.ServletActionContext;
import org.framework.util.DateUtil;
import org.framework.util.FileUtil; import com.lowagie.text.BadElementException;
import com.lowagie.text.Cell;
import com.lowagie.text.Document;
import com.lowagie.text.DocumentException;
import com.lowagie.text.Element;
import com.lowagie.text.Font;
import com.lowagie.text.PageSize;
import com.lowagie.text.Paragraph;
import com.lowagie.text.Table;
import com.lowagie.text.pdf.BaseFont;
import com.lowagie.text.rtf.RtfWriter2;
import com.lowagie.text.rtf.style.RtfFont;
import com.opensymphony.xwork2.ActionSupport; @SuppressWarnings("serial")
public class UserAction extends ActionSupport{ private String fileName;
private InputStream inputStream;
public String getFileName() {
try {
String filename = new String(this.fileName.getBytes("GBK"),"ISO8859-1");
return filename;
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
return "code";
}
}
public void setFileName(String fileName) {
this.fileName = fileName;
} public InputStream getInputStream() {
return inputStream;
}
public void setInputStream(InputStream inputStream) {
this.inputStream = inputStream;
}
public String test() throws DocumentException, IOException{
String tempFolder = ServletActionContext.getServletContext().getRealPath("/temp/"+UUID.randomUUID());
FileUtil.newFolder(tempFolder);
String doc_outlearn=tempFolder+"/temp.doc";
File file =null;
try {
file = new File(doc_outlearn);
Document document = new Document(PageSize.A4, 50, 50, 50, 50);
RtfWriter2.getInstance(document, new FileOutputStream(file));
document.open();
exportWords(document);
document.close();
this.setFileName("SK1995.doc");
this.inputStream =new java.io.FileInputStream(doc_outlearn);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally {
file.deleteOnExit();
}
return "exportFile";
} public void exportWords(Document document) throws DocumentException, 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("\n\nSK个人项目\n申\t请\t书\n\n\n\n",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("\n\n"+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) throws BadElementException
{
Cell cell=new Cell();
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= new Paragraph(value, contextFont);
label.setSpacingBefore(spacing);
label.setSpacingAfter(spacing);
cell.addElement(label);
return cell;
}
public Cell fillCellWithBottomBorder(String value, RtfFont contextFont,int align,int spacing,int colspans,int rowspan) throws BadElementException
{
Cell cell=new Cell();
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= new Paragraph(value, contextFont);
label.setSpacingBefore(spacing);
label.setSpacingAfter(spacing);
cell.addElement(label);
return cell;
}
public Cell fillCell(String value, RtfFont contextFont,int align,int spacing,int colspans) throws BadElementException
{
Cell cell=new Cell();
cell.setHorizontalAlignment(align);
cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
if (colspans>0)
{
cell.setColspan(colspans);
}
Paragraph label= new Paragraph(value, contextFont);
label.setSpacingBefore(spacing);
label.setSpacingAfter(spacing);
cell.addElement(label);
return cell;
}
public Cell fillCell(String value, RtfFont contextFont,int align,int spacing,int colspans,int rowspan) throws BadElementException
{
Cell cell=new Cell();
cell.setHorizontalAlignment(align);
cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
if (colspans>0)
{
cell.setColspan(colspans);
}
if (rowspan>0)
{
cell.setRowspan(rowspan);
}
Paragraph label= new Paragraph(value, contextFont);
label.setSpacingBefore(spacing);
label.setSpacingAfter(spacing);
cell.addElement(label);
return cell;
}
public Paragraph setParagraphStyle(Font font , float firstLineIndent , float leading , float indentationRight , int alignment, int spacing)
{
Paragraph _paragraph = new Paragraph();
_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
完成!