Java操作Excel之下载模板

本文介绍如何用Java实现从服务器下载Excel模板,包括设置HTTP响应头、读取文件流及输出等步骤。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Java操作Excel之下载模板

本文章描述使用Java开发语言来下载服务器上已存在的模板案例,下篇文章会具体描述读取数据库数据到指定的excel模板。大体分为以下三部分:

  • 读取服务器上的 Excel模板路径
  • 设置http请求的相应头和数据类型
  • 读取文件流,输出流

前台参数

参数含义
templateName模板名称
fileName下载后的文件名称

后台代码

public static final void downloadTemplate(HttpServletRequest request, HttpServletResponse response) {
        // 模板名称
        String templateName = request.getParameter("templateName");
        // 下载文件名
        String fileName = request.getParameter("fileName");
        try {
            fileName = new String(fileName.getBytes("GBK"), "ISO-8859-1");
        } catch (UnsupportedEncodingException e1) {
            e1.printStackTrace();
        }
        // 获取模板位置,读取数据库(也可以读取配置文件或写死)
        String templatePath = PubConfig.getProperty("EXCEL_TEMPLATE_PATH");
        // 实际位置
        String path = templatePath + File.separator + templateName;
        System.out.println(path);
        // 1.设置文件ContentType类型,这样设置,会自动判断下载文件类型
        response.setContentType("multipart/form-data");
        // 2.设置文件头:最后一个参数是设置下载文件名
        response.setHeader("Content-Disposition", "attachment;fileName="
                + fileName);
        response.addHeader("Content-Type", "application/vnd.ms-excel");
        OutputStream out;
        // 通过文件路径获得File对象(假如此路径中有一个download.pdf文件)
        File file = new File(path);
        try {
            FileInputStream inputStream = new FileInputStream(file);
            // 3.通过response获取OutputStream对象(out)
            out = response.getOutputStream();
            byte[] buffer = new byte[512];
            int b = inputStream.read(buffer);
            while (b != -1) {
                // 4.写到输出流(out)中
                out.write(buffer, 0, b);
                b = inputStream.read(buffer);
            }
            inputStream.close();
            out.close();
            out.flush();

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

是不是简单易懂


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值