Java后台下载Excel模板并输出到浏览器上的样例

上代码!

/**
     * 下载模板
     *
     * @throws IOException
     */

    @RequestMapping("/exportExcel")
    @ResponseBody
    public Object exportExcel(HttpServletResponse response) throws IOException {
        response.setCharacterEncoding("utf-8");
        OutputStream out = null;
        //表头列名
        List<String> title = new ArrayList<>();
        title.add("第一列");
        title.add("第二列");
        // 2.1创建excel对象
        HSSFWorkbook workbook = new HSSFWorkbook();
        HSSFCellStyle stylePALE_BLUE = workbook.createCellStyle();
        stylePALE_BLUE.setFillForegroundColor(IndexedColors.PALE_BLUE.getIndex());
        stylePALE_BLUE.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        // 2.2创建工作表sheet
        HSSFSheet sheet = workbook.createSheet();
        // 添加表头
        HSSFRow row = sheet.createRow(0);
        // 设置高度
        row.setHeight((short) (17.5 * 20));
        // 插入第一行数据的表头
        HSSFCell cell = null;
        HSSFPalette pt = workbook.getCustomPalette();
        for (int i = 0; i < title.size(); i++) {
            // 宽度
            sheet.setColumnWidth(i, 21 * 256);
            // 设置样式赋值
            cell = row.createCell(i);
            pt.setColorAtIndex(HSSFColor.LIME.index, (byte) 0, (byte) 176, (byte) 80);
            cell.setCellStyle(stylePALE_BLUE);
            cell.setCellValue(title.get(i));
        }
        out = response.getOutputStream();
        String fileName = "test.xls";// 文件名
        response.setContentType("application/x-msdownload");
        response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileName, "UTF-8"));
        workbook.write(out);
        out.close();
        return null;
    }

戴卡五楼

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值