今天很荣幸又破解一现实难题:自动生成并导出word文档

先看页面效果:

word效果:

代码:

  1. 先搭建struts2项目
  2. 创建action,并在struts.xml完成注册
  3. <?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

完成!

自动生成并导出word文档的更多相关文章

  1. NPOI插件生成导出word文档

    因为之前没有接触NPOI过这个插件,所以几乎都是自己一边百度摸索一边学习. 这个插件对于Excel的数据导入和导出,可以说是很方便了, 但是对于导出word文档,可以说是很少的,百度了很多....也不 ...

  2. PHP网页导出Word文档的方法分离

    今天要探讨的是PHP网页导出Word文档的方法,使用其他语言的朋友也可以参考,因为原理是差不多的. 原理 一般,有2种方法可以导出doc文档,一种是使用com,并且作为php的一个扩展库安装到服务器上 ...

  3. powerdesigner连接postgresql数据库生成pdm及word文档

    1.准备软件: powerdesigner165与postgresql的驱动:psqlodbc_11_01_0000 2.安装并破解完成powerdesigner165 参看链接:https://ww ...

  4. .NET通过调用Office组件导出Word文档

    .NET通过调用Office组件导出Word文档 最近做项目需要实现一个客户端下载word表格的功能,该功能是用户点击"下载表格",服务端将该用户的数据查询出来并生成数据到Word ...

  5. C# 导出word文档及批量导出word文档(4)

          接下来是批量导出word文档和批量打印word文件,批量导出word文档和批量打印word文件的思路差不多,只是批量打印不用打包压缩文件,而是把所有文件合成一个word,然后通过js来调用 ...

  6. 【工具篇】利用DBExportDoc V1.0 For MySQL自动生成数据库表结构文档

    对于DBA或开发来说,如何规范化你的数据库表结构文档是灰常之重要的一件事情.但是当你的库,你的表排山倒海滴多的时候,你就会很头疼了. 推荐一款工具DBExportDoc V1.0 For MySQL( ...

  7. Java 用Freemarker完美导出word文档(带图片)

    Java  用Freemarker完美导出word文档(带图片) 前言 最近在项目中,因客户要求,将页面内容(如合同协议)导出成word,在网上翻了好多,感觉太乱了,不过最后还是较好解决了这个问题. ...

  8. poi根据模板导出word文档

    POI结构与常用类 Apache POI是Apache软件基金会的开源项目,POI提供API给Java程序对Microsoft Office格式档案读和写的功能. .NET的开发人员则可以利用NPOI ...

  9. 【Java】用Freemarker完美导出word文档(带图片)

    Java  用Freemarker完美导出word文档(带图片) 前言 最近在项目中,因客户要求,将页面内容(如合同协议)导出成word,在网上翻了好多,感觉太乱了,不过最后还是较好解决了这个问题. ...

随机推荐

  1. 3553: [Shoi2014]三叉神经树(树链剖分)

    这道题特别恶心,首先我们可以发现更改的就是出现连续的一或二,那么就用线段树+树链剖分找到这个范围 想到是不难想,就是打起来恶心罢了= = CODE: #include<cstdio> #i ...

  2. WP8.1程序开发,可视树VisualTreeHelper类的使用

    对于可视树的使用,很久之前就接触了, 一方面当时知识太浅根本看不懂,就放下没看了: 另一方面,也没用到,就没往这方面努力研究学习: 现在好了,遇到问题了,正好涉及到VisualTreeHelper的使 ...

  3. 基于CPS变换的尾递归转换算法

    前言 众所周知,递归函数容易爆栈,究其原因,便是函数调用前需要先将参数.运行状态压栈,而递归则会导致函数的多次无返回调用,参数.状态积压在栈上,最终耗尽栈空间. 一个解决的办法是从算法上解决,把递归算 ...

  4. 关于Monkey的一切都在这里

    关于Monkey的一切都在这里 版权声明: 本账号发布文章均来自公众号,承香墨影(cxmyDev),版权归承香墨影所有. 允许有条件转载,转载请附带底部二维码. 一.什么是Monkey Monkey是 ...

  5. 模拟做饭系统(java+线程中的join方法)

    (一)项目框架分析 妈妈要去做饭,发现没有酱油,让儿子去买酱油,然后回来做饭. 根据面向对象的思想,有两个对象,妈妈和儿子 主要有两个方法: (一)没有线程控制(即儿子没有买酱油回来妈妈就做好饭了)+ ...

  6. 配置apache

    1. 修改httpd.conf文件 # vi  /usr/local/apache/conf/httpd.conf 1) 设置根目录的路径 根目录是指Apache存放配置文件和日志文件的目录,配置参数 ...

  7. nodejs中的路由

    一.路由初步 url.parse(string).query | url.parse(string).pathname | | | | | ------ -------------------http ...

  8. LeetCode 2. Add Two Numbers 解题报告

    题意: 有两个链表,它们表示逆序的两个非负数.例 (2 -> 4 -> 3)表示342,求两个数字的和,并用同样的方式逆序输出.如342+465 = 807,你需要把结果表达为(7 -&g ...

  9. Linux服务器下Java环境搭建

    前言: 在centOS下,像阿里云等都预先设置了jdk,不过不是SUN的java JDK,一般情况要重新装jdk,而且一般情况下自己装的Jdk相对来说易控制版本,稳定性更高.所以以下是我卸载预装jdk ...

  10. ACM 子串和

    子串和 时间限制:5000 ms  |  内存限制:65535 KB 难度:3   描述 给定一整型数列{a1,a2...,an},找出连续非空子串{ax,ax+1,...,ay},使得该子序列的和最 ...