jsp 页面生成word文档

       现场需要一个内容自动生成word文档,并自动上传到ftp的功能。

       功能需求:一个维护程序,只需要填写时间和文档的基础信息,根据时间去取其他程序的数据,进行归总,并按照现场给的模板进行生成word文档。

        解决方案:1.将现场提供的word的模板另存为html文件,生成之后除了html文件外,还有一些其他xml等文件,在html的head标签会引用这些文件,将其全部删除。

   2.将html里代码复制到jsp文件内,jsp代码再添加两行代码:

<%
response.setHeader("Content-disposition","attachment;filename=text.doc");
%>
以及head便签内添加:

<!--[if gte mso 9]><xml><w:WordDocument><w:View>Print</w:View><w:TrackMoves>false</w:TrackMoves><w:TrackFormatting/><w:ValidateAgainstSchemas/><w:SaveIfXMLInvalid>false</w:SaveIfXMLInvalid><w:IgnoreMixedContent>false</w:IgnoreMixedContent><w:AlwaysShowPlaceholderText>false</w:AlwaysShowPlaceholderText><w:DoNotPromoteQF/><w:LidThemeOther>EN-US</w:LidThemeOther><w:LidThemeAsian>ZH-CN</w:LidThemeAsian><w:LidThemeComplexScript>X-NONE</w:LidThemeComplexScript><w:Compatibility><w:BreakWrappedTables/><w:SnapToGridInCell/><w:WrapTextWithPunct/><w:UseAsianBreakRules/><w:DontGrowAutofit/><w:SplitPgBreakAndParaMark/><w:DontVertAlignCellWithSp/><w:DontBreakConstrainedForcedTables/><w:DontVertAlignInTxbx/><w:Word11KerningPairs/><w:CachedColBalance/><w:UseFELayout/></w:Compatibility><w:BrowserLevel>MicrosoftInternetExplorer4</w:BrowserLevel><m:mathPr><m:mathFont m:val="Cambria Math"/><m:brkBin m:val="before"/><m:brkBinSub m:val="--"/><m:smallFrac m:val="off"/><m:dispDef/><m:lMargin m:val="0"/> <m:rMargin m:val="0"/><m:defJc m:val="centerGroup"/><m:wrapIndent m:val="1440"/><m:intLim m:val="subSup"/><m:naryLim m:val="undOvr"/></m:mathPr></w:WordDocument></xml><![endif]-->  

这行代码用处:生成的word文件,打开模式默认设为页面视图模式,因为生成的word文档为web版本,如果不加这行代码,默认打开为web版视图模式。

                           3.后台处理代码:

                           

String url ="";     //word模板jsp文件存在的路径地址
HttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet(url);                  //获取模板的数据
InputStream instream = null;
FTP ftp = null;
try{
      HttpResponse resp = client.execute(get);
      HttpEntity entity = resp.getEntity();
      instream = entity.getContent();
      
      String newDocId = "";    //主键值 
      ftp = FTP.getInstanceByDocId(db, newDocId);           //创建ftp     
      if ((ftp == null) || (!ftp.createConnection())) {
        throw new LiemsException("保存失败,请检查数据库和FTP连接!");
      }
      ftp.upload(newDocId, instream);                   //上传
} catch (ClientProtocolException e)
    {
      Log.error(e);
    }
    catch (IOException e)
    {
      Log.error(e);
    }
    catch (Exception e)
    {
      Log.error(e);
      db.rollback();
    }
    finally
    {
      if (instream != null) {
        try
        {
          instream.close();
        }
        catch (IOException e)
        {
          Log.error(e);
        }
      }
      get.releaseConnection();
      client.getConnectionManager().shutdown();
      if (ftp != null) {
        ftp.closeConnection();
      }
    }
ps:特别注意一下,生成的word编辑之后,不能直接保存,需要另存为word模板,因为生成的格式还是web的,需要自另存为转换为word格式

要将 JSP 页面导出为 Word 文档,可以使用 Java 中的 POI 库来实现。具体步骤如下: 1. 添加 POI 库的依赖,可以在 Maven 中添加以下依赖: ```xml <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>4.1.2</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>4.1.2</version> </dependency> ``` 2. 在 JSP 页面中添加导出按钮,点击该按钮时触发导出事件,将 JSP 页面中的内容导出为 Word 文档。 ```jsp <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ page import="java.io.*, org.apache.poi.xwpf.usermodel.*" %> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>导出 Word 文档</title> </head> <body> <h1>将 JSP 页面导出为 Word 文档</h1> <form action="exportWord.jsp" method="post"> <input type="submit" value="导出 Word"> </form> <%! public void exportWord() throws IOException { // 创建 Word 文档对象 XWPFDocument document = new XWPFDocument(); // 创建段落对象 XWPFParagraph paragraph = document.createParagraph(); // 设置段落文本 paragraph.createRun().setText("这是导出的 Word 文档内容!"); // 输出 Word 文档 OutputStream out = response.getOutputStream(); response.setContentType("application/msword"); response.setHeader("Content-Disposition", "attachment;filename=test.docx"); document.write(out); out.flush(); out.close(); } %> <%-- 导出 Word 文档 --%> <%if (request.getParameter("export") != null) { exportWord(); }%> </body> </html> ``` 在上述示例代码中,使用 `XWPFDocument` 创建 Word 文档对象,使用 `XWPFParagraph` 创建段落对象,最后将 Word 文档导出到浏览器中。在导出时,需要设置响应的 Content-Type 和 Content-Disposition 头,使浏览器能够正确地识别导出的文件类型并进行下载。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值