JAVA POI实现Word填充(DOC)

这种填充技术后的文件是doc格式的可以下载word中的文本样式。

  1. 导入两个必须的Jar包:poi-3.10.1.jar和poi-scratchpad-3.10.1.jar

  2. 如果报filesystem错误,应该是引用的这两个包的版本不一样,所以一定要保持版本一致。

  3. 直接将内容导出成DOC文件:

     /**     * 导出Word文件

         * @param destFile 目标文件路径

         * @param fileContent 要导出的文件内容

         */public static int exportDoc(String destFile,String fileContent){

    try {

    ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(fileContent.getBytes("UTF-8"));

    POIFSFileSystem fileSystem = new POIFSFileSystem();

    DirectoryEntry directory = fileSystem.getRoot();

    directory.createDocument("WordDocument", byteArrayInputStream);

     FileOutputStream fileOutputStream = new FileOutputStream(destFile);

    fileSystem.writeFilesystem(fileOutputStream);

    byteArrayInputStream.close();

    fileOutputStream.close();

     return 1;

    } catch (IOException e) {return 0;

     }

    }

    这个导出只是对文字Word做的导出。

    用法:

    exportDoc("C:\\12.doc", "exportDoc导出Word");

  4. 使用模板导出Doc的话需要先定义好模板内容。

    例如模板内容如下图所示。

  5. /**     * 读取word模板并替换变量

         * @param templatePath 模板路径

         * @param contentMap 要替换的内容

         * @return word的Document

         */

        public static HWPFDocument replaceDoc(String templatePath, Map<String, String> contentMap) {

            try {

                // 读取模板

    FileInputStream tempFileInputStream = new FileInputStream(new File(templatePath));

    HWPFDocument document = new HWPFDocument(tempFileInputStream);

                // 读取文本内容

                Range bodyRange = document.getRange();

                // 替换内容

                for (Map.Entry<String, String> entry : contentMap.entrySet()) {

                    bodyRange.replaceText("${" + entry.getKey() + "}", entry.getValue());

                }

                return document;

            } catch (Exception e) {

                return null;

            }

        }

  6. 调用方法如下:

    Map<String, String> contentMap=new HashMap<String, String>();

    contentMap.put("name", "飞翔家族");

    contentMap.put("age", "123");

    contentMap.put("email", "1231231231@123.com");

    HWPFDocument document = replaceDoc("C:\\template.doc", contentMap);

            if(document != null){

             ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();

                try {

                    document.write(byteArrayOutputStream);

                    OutputStream outputStream = new FileOutputStream(destFile);

                    outputStream.write(byteArrayOutputStream.toByteArray());

                    outputStream.close();

                } catch (IOException e) {                            }

            }

  7. 使用模板导出DOC文件我们还可以使用其他的方法。

    我们还是先需要制作好DOC模板文件,然后另存为XML文件。

    使用velocity,将数据填充,导出成DOC文件。

  8. 这里介绍的都是最简单的方法,直接导出文本Word,如果要导出复杂一点的Word,请再查阅。
     

  9. 读取doc文件的内容

  • 5
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
实现文档填充并下载多个文件,可以按照以下步骤进行: 1. 使用Java POI库创建模板文件和填充数据 2. 将填充后的模板文件保存到服务器上的指定位置 3. 使用Java Servlet编写一个下载文件的接口,实现多文件下载 4. 在前端页面上添加下载按钮,调用下载接口下载多个文件 下面是一个简单的实现示例: 1. 创建模板文件和填充数据 假设我们有两个需要填充数据的模板文件,一个是word文档,一个是excel表格。我们可以使用Java POI库来创建这些模板文件,并将数据填充到模板文件中。具体代码如下: ```java // 创建word文档模板并填充数据 XWPFDocument doc = new XWPFDocument(new FileInputStream("template.docx")); Map<String, Object> data = new HashMap<>(); data.put("name", "张三"); data.put("age", 30); doc = WordUtils.fillDocWithData(doc, data); // 创建excel表格模板并填充数据 XSSFWorkbook workbook = new XSSFWorkbook(new FileInputStream("template.xlsx")); Sheet sheet = workbook.getSheetAt(0); Map<String, Object> data2 = new HashMap<>(); data2.put("name", "李四"); data2.put("age", 25); workbook = ExcelUtils.fillWorkbookWithData(workbook, sheet, data2); ``` 2. 保存填充后的模板文件到服务器 ```java // 保存填充后的word文档到服务器 FileOutputStream out = new FileOutputStream("filled.docx"); doc.write(out); out.close(); // 保存填充后的excel表格到服务器 FileOutputStream out2 = new FileOutputStream("filled.xlsx"); workbook.write(out2); out2.close(); ``` 3. 编写下载文件的接口 我们可以使用Java Servlet来实现下载多个文件的接口。具体代码如下: ```java @WebServlet("/download") public class DownloadServlet extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 获取需要下载的文件名列表 String[] fileNames = request.getParameterValues("fileName"); // 设置响应头,告诉浏览器下载文件 response.setContentType("application/octet-stream"); response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("files.zip", "UTF-8")); // 创建zip压缩文件 ZipOutputStream zipOut = new ZipOutputStream(response.getOutputStream()); for (String fileName : fileNames) { // 将指定文件添加到zip压缩文件中 File file = new File(fileName); FileInputStream in = new FileInputStream(file); zipOut.putNextEntry(new ZipEntry(file.getName())); byte[] buffer = new byte[1024]; int len; while ((len = in.read(buffer)) > 0) { zipOut.write(buffer, 0, len); } zipOut.closeEntry(); in.close(); } zipOut.flush(); zipOut.close(); } } ``` 4. 在前端页面上添加下载按钮 在前端页面上添加一个下载按钮,并在点击按钮时调用下载接口,传递需要下载的文件名列表即可。具体代码如下: ```html <button onclick="downloadFiles()">下载文件</button> <script> function downloadFiles() { var fileNames = ["filled.docx", "filled.xlsx"]; var url = "/download?fileName=" + fileNames.join("&fileName="); window.open(url); } </script> ``` 这样,当用户点击下载按钮时,浏览器会弹出下载对话框,用户可以选择保存多个文件到本地。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值