javaUtil---导出数据到word表格中后,下载word文档

本文介绍了如何使用JavaUtils在Controller中实现数据导出到Word表格,并下载Word文档。通过ResponseEntity处理文件导出时的编码问题,获取模板文件路径,使用XWPFDocument技术操作Word文档,配置docxMapping Bean,以及详细说明了替换模板内容和单元格数据的方法,其中关键在于用key匹配并替换模板中的内容。
摘要由CSDN通过智能技术生成

为满足将对应数据插入到word表格中并导出word模板,下载word模板。
utils的 controller里的方法:
1.利用ResponseEntity 实体进行文件导出,以解决导出文件名称自定,防止乱码的效果。因为 ResponseEntity 可以对http协议的header进行设定来设定编码格式。

public static final String TargetDir = "targetfile" + File.separator;
public static final String DownloadDir = "downloadfile" + File.separator;
public static ResponseEntity<byte[]> fileDownload(File targetfile,
            String filename, HttpServletRequest request) {
        try {
            if (targetfile.exists() && targetfile.isFile()) {
                HttpHeaders headers = new HttpHeaders();
                headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);//设置header的contenttype为字节流。
                String userAgent = request.getHeader("User-Agent");//通过userAgent判断浏览器类型
                byte[] bytes = userAgent.contains("MSIE") ? filename.getBytes()
                        : filename.getBytes("UTF-8"); // name.getBytes("UTF-8")处理safari的乱码问题,解决文件名乱码问题
                String fileName = new String(bytes, "ISO-8859-1");
                headers.set(HttpHeaders.CONTENT_DISPOSITION,
                        "attachment; filename=\"" + fileName + "\"");//设置CONTENT_DISPOSITION使浏览器打开文件下载对话框

                byte[] readFileToByteArray = null;
                readFileToByteArray = FileUtils.readFileToByteArray(targetfile);
                return new ResponseEntity<byte[]>(readFileToByteArray, headers,
                        HttpStatus.OK);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return new ResponseEntity<byte[]>(HttpStatus.INTERNAL_SERVER_ERROR)
    }

2.获取模板文件路径
//params是一个数据map集合,此数据集合用于将数据插入对应模板的对应位置。然后利用XWPFDocument相关技术操作word文档。

public static String getDocxPath(HttpServletRequest request, String type,
            Map<String, String> params) {
        Map<String, Object> params1 = new HashMap<String, Object>();

        for (Entry<String, String> entry : params.entrySet()) {
            params1.put(entry.getKey(), entry.getValue());
        }

        return getDocxPathIncludePic(request, type, params1);
    }
public static String getDocxPathIncludePic(HttpServletRequest request,
            String type, Map<String, Object> params) {

        Map<String, String> docxMapping = SpringContextHolder
                .getBean("docxMapping");
        String fileTargetPath = docxMapping.get(type);//此tape为配置文件里的key值。通过key值获得对应模板的名字
        String tf = null;
        if (fileTargetPath != null) {
            File dir = new File(request.get
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值