Spring Boot将查询后的数据导出为Excle

1.pom中添加依赖

		<!--  数据导出Excle依赖-->
        <!--  官网:http://poi.apache.org/index.html-->
        <!--  API:http://poi.apache.org/apidocs/4.1/-->
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>4.0.1</version>
        </dependency>

2.创建ExportExcel工具类

//fieList为表头数据  getMessAboutExcle为数据库中查询后的结果
public HSSFWorkbook exportExcel(List<FieldParameter> fieList,List<Map<String, Object>> getMessAboutExcle)
    {

        //实例化Excel表格
        HSSFWorkbook workbook = new HSSFWorkbook();
        // 创建第一个Sheet页
        HSSFSheet sheet = workbook.createSheet("第一个Sheet页");
        // 设置表格默认列宽度为15个字节
        sheet.setDefaultColumnWidth((short) 15);
        // 生成一个样式
        HSSFCellStyle style = workbook.createCellStyle();
        // 创建一个居中格式
        style.setAlignment(HorizontalAlignment.CENTER);
        // 产生表格标题行
        HSSFRow row = sheet.createRow(0);

		//向标题行中插入列
        for (short i = 0; i < fieList.size(); i++)
        {
            HSSFCell cell = row.createCell(i);
            cell.setCellStyle(style);
            // fieList.get(i).getfFieldNameCn() : 表头名
            HSSFRichTextString text = new HSSFRichTextString(fieList.get(i).getfFieldNameCn());
            cell.setCellValue(text);
        }
		//创建行,并向其中插入数据
        for(short s = 0 ; s < getMessAboutExcle.size() ; s++){
            row = sheet.createRow(s + 1);
            for(short t = 0;t<fieList.size();t++){
                HSSFCell cell = row.createCell(t);
                cell.setCellStyle(style);
                String en = fieList.get(t).getfFieldNameEn();
                cell.setCellValue(getMessAboutExcle.get(s).get(en).toString());
            }
        }
    return workbook;
    }

3.引用

	@ResponseBody
    @RequestMapping("/downloadExporExcle")
    public void downloadExporExcle(HttpServletResponse response) {

		.......

        ExportExcel export = new ExportExcel();
        HSSFWorkbook hs = export.exportExcel(fieList, getMessAboutExcle);

        try {

            // 清空response
            response.reset();
            // 设置response的Header,设置下载文件名,如此处理防止中文乱码
            response.setHeader("Content-Disposition", "inline;fileName=\"" + new String((layerparame.getpNameCn() + ".xls").getBytes("utf-8"),"ISO8859-1") + "\"");
            response.setContentType("application/vnd.ms-excel;charset=utf-8");

            OutputStream os = response.getOutputStream();
            hs.write(os);
            os.close();

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值