自动生成并导出word文档

时间:2021-09-28 23:36:39

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

先看页面效果:

自动生成并导出word文档

word效果:

自动生成并导出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. &period;NET通过调用Office组件导出Word文档

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

  5. C&num; 导出word文档及批量导出word文档(4)

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

  6. 【工具篇】利用DBExportDoc V1&period;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. webpack&period;optimize&period;CommonsChunkPlugin插件的使用

    方式一,传入字符串参数 new webpack.optimize.CommonsChunkPlugin('common.js'), // 默认会把所有入口节点的公共代码提取出来,生成一个common. ...

  2. iOS UIKit:TabBar Controller

    1 结构剖析 IOS中的标签导航其实是一个UITabBarController对象,其也是一个Container View Controller.UITabBarController对象创建和管理了一 ...

  3. Problem 1183 - 排列

    #include<iostream> #include<vector> #include<algorithm> using namespace std; int c ...

  4. Cannot access empty property

    致命错误:不能够进入此空值,位于E:\sunlion\web\down\class\db_sql.php 代码 <?php Class TestClass1{ var $class2; publ ...

  5. c&plus;&plus; 静态多态与动态多态

    多态polymorphism是指具有多种形态的情况,它能根据单一的标记关联不同的行为.多态是面向对象程序设计的基础.在面向对象程序设计中的多态是一种运行时的多态.C++中有两种多态,称为动多态(运行时 ...

  6. JS 小技巧整理

    一.javascript中调用函数并不一定严格执行指定的参数个数.(函数定义时的参数个数和调时指定的参数个数并不一定要相等) function showInfo(arg1) { var defindl ...

  7. Exception in Spark

    1: Exception in thread "main" org.apache.spark.SparkException: org.apache.spark.streaming. ...

  8. 温馨小程序前端布局Flex

    伸缩容器支持的属性有: 1,display 2,flex-direction 3,flex-wrap 4,flex-flow 5,justify-content 6,align-items 7,ali ...

  9. bootstrap-datepicker 开始时间-结束时间 thinkphp

    <!DOCTYPE html> <head> <title>开始-结束时间测试</title> </head> <body> & ...

  10. 1497&colon; &lbrack;NOI2006&rsqb;最大获利

    新的技术正冲击着手机通讯市场,对于各大运营商来说,这既是机遇,更是挑战.THU集团旗下的CS&T通讯公司在新一代通讯技术血战的前夜,需要做太多的准备工作,仅就站址选择一项,就需要完成前期市场研 ...