Java实现数据自动填充到WORD文档并下载

模拟业务场景:假设有一个OA系统,员工在里面填了请假申请,填好后可以通过下载自动生成一个word文档的请假条。比如数据表有姓名,请假原因,时间等字段,将这些字段填充到一个word模板中。

1. 准备word模板

 注意:模板是通过 {{}} 双括号的格式来表明哪些字段是代码实现自动填充的,比如我表里面的请假原因字段名叫 reason ,那么在模板中就写 {{reason}},这样就可以识别了,其他格式暂未测试。

将模板放到项目中resources下面的template文件夹中

位置如下:

2. maven依赖(某些版本有冲突)

  
        <dependency>
            <groupId>com.deepoove</groupId>
            <artifactId>poi-tl</artifactId>
            <version>1.5.1</version>
        </dependency>

        <!-- 1.5.1版本对应poi 3.16版本-->
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>3.16</version>
        </dependency>
 

3. 代码实现

3.1 实体类

import java.io.Serializable;
import java.util.Date;

/**
 * @author YuePeng
 * @date 2022/12/28 15:12
 * 这里只是模拟部分字段,并非真实表结构
 */
public class LeaveForm implements Serializable {
    private static final long serialVersionUID = -5652177874505967327L;
    
    private String id;
    // 请假人
    private String name;
    // 请假原因
    private String reason;
    // 请假时间
    private Date leaveDate;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getReason() {
        return reason;
    }

    public void setReason(String reason) {
        this.reason = reason;
    }

    public Date getLeaveDate() {
        return leaveDate;
    }

    public void setLeaveDate(Date leaveDate) {
        this.leaveDate = leaveDate;
    }
}

3.2 Dao层

package com.worm.dao;

import com.worm.backup.LeaveForm;
import org.apache.ibatis.annotations.Mapper;

@Mapper
public interface LeaveFormDao extends tk.mybatis.mapper.common.Mapper<LeaveForm> {
}

3.3 ServiceImpl实现类

package com.worm.service.impl;

import com.deepoove.poi.XWPFTemplate;
import com.worm.backup.LeaveForm;
import com.worm.dao.LeaveFormDao;
import com.worm.service.LeaveFormService;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.Map;

public class LeaveFormServiceImpl implements LeaveFormService {
    @Autowired
    private LeaveFormDao leaveFormDao;

    @Override
    public byte[] downloadWord(String id) {
            LeaveForm query = new LeaveForm();
            query.setId(id);
            //根据id查找数据
            LeaveForm leaveForm = leaveFormDao.selectByPrimaryKey(query);
            // 获取文件流
            InputStream stream = LeaveFormServiceImpl.class.getClassLoader().getResourceAsStream("template/downloadWord.docx");
            // 填充数据
            Map<String, String> data = new HashMap<>();
            data.put("name", leaveForm.getName());
            data.put("reason", leaveForm.getReason());
            data.put("date", new SimpleDateFormat("yyyy年MM月dd日").format(leaveForm.getLeaveDate()));

            XWPFTemplate template = XWPFTemplate.compile(stream).render(data);
            //输出流
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            return getBytes(template, outputStream);
    }

    private byte[] getBytes(XWPFTemplate template, ByteArrayOutputStream os) {
        byte[] bytes = new byte[0];
        try {
            template.write(os);
            bytes = os.toByteArray();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                template.close();
                os.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return bytes;
    }
}

3.4 Service接口层

public interface LeaveFormService {

    byte[] downloadWord(String id);

}

3.5 Controller层

package com.worm.controller;

import com.worm.service.LeaveFormService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.nio.charset.StandardCharsets;

@RestController
@RequestMapping("/leaveFrom")
public class LeaveFormController {

    @Autowired
    private LeaveFormService leaveFormService;

    @RequestMapping(value = "/downloadWord", method = RequestMethod.GET)
    public ResponseEntity downloadWord(
             @RequestParam(required = true) String id) {
        byte[] bytes = leaveFormService.downloadWord(id);
        String fileName = "downloadWord.docx";
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        headers.setContentDispositionFormData("attachment", fileName, StandardCharsets.UTF_8);
        return new ResponseEntity(bytes, headers, HttpStatus.OK);
    }

}

  • 4
    点赞
  • 21
    收藏
    觉得还不错? 一键收藏
  • 16
    评论
实现文档填充下载多个文件,可以按照以下步骤进行: 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> ``` 这样,当用户点击下载按钮时,浏览器会弹出下载对话框,用户可以选择保存多个文件到本地。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 16
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值