• JAVA将数据库数据导出为Excel


    前注:来源于网络

    描述:客户端通过HTTP的GET方式请求,在后台处理并从数据库中查询到数据列表,最终将数据列表生成HTTP相应流返回到客户端,客户端即实现对数据的Excel导出。

    1. 依赖

    <!-- https://mvnrepository.com/artifact/org.apache.poi/poi -->
    <dependency>
        <groupId>org.apache.poi</groupId>
        <artifactId>poi</artifactId>
        <version>3.6</version>
    </dependency>

    2. 工具类

    package com.xfc.util;
    
    import org.apache.poi.hssf.usermodel.HSSFCell;
    import org.apache.poi.hssf.usermodel.HSSFCellStyle;
    import org.apache.poi.hssf.usermodel.HSSFRow;
    import org.apache.poi.hssf.usermodel.HSSFSheet;
    import org.apache.poi.hssf.usermodel.HSSFWorkbook;
    
    /**
     * @Auther: xfc
     * @Date: 2019/5/20 0020 14:21
     * @Description:
     */
    public class ExcelUtil {
    
        /**
         * 导出Excel
         *
         * @param sheetName sheet名称
         * @param title     标题
         * @param values    内容
         * @param wb        HSSFWorkbook对象
         * @return
         */
        public static HSSFWorkbook getHSSFWorkbook(String sheetName, String[] title, String[][] values, HSSFWorkbook wb) {
    
            // 第一步,创建一个HSSFWorkbook,对应一个Excel文件
            if (wb == null)
                wb = new HSSFWorkbook();
    
            // 第二步,在workbook中添加一个sheet,对应Excel文件中的sheet
            HSSFSheet sheet = wb.createSheet(sheetName);
    
            // 第三步,在sheet中添加表头第0行,注意老版本poi对Excel的行数列数有限制
            HSSFRow row = sheet.createRow(0);
    
            // 第四步,创建单元格,并设置值表头 设置表头居中
            HSSFCellStyle style = wb.createCellStyle();
            style.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 创建一个居中格式
    
            //声明列对象
            HSSFCell cell = null;
    
            //创建标题
            for (int i = 0; i < title.length; i++) {
                cell = row.createCell(i);
                cell.setCellValue(title[i]);
                cell.setCellStyle(style);
            }
    
            //创建内容
            for (int i = 0; i < values.length; i++) {
                row = sheet.createRow(i + 1);
                for (int j = 0; j < values[i].length; j++) {
                    //将内容按顺序赋给对应的列对象
                    row.createCell(j).setCellValue(values[i][j]);
                }
            }
            return wb;
        }
    }

    3. 调用

    因为业务简单,我这里在controller层就直接处理了

        /**
         * 根据条件将数据导出为Excel
         * 如果需要浏览器发送请求时即下载Excel,就不能用ajax进行传输,所以这里用GET方式进行提交
         *
         * @return
         */
        @ResponseBody
        @RequestMapping(value = "/exportExcel", method = RequestMethod.GET)
        public void exportExcel(HttpServletRequest request, HttpServletResponse response) {
            QRRecord obj = new QRRecord();
            obj.setPageStart(Integer.valueOf(request.getParameter("pageStart")));
            obj.setPageSize(Integer.valueOf(request.getParameter("pageSize")));
            obj.setTerm(request.getParameter("term"));
            List<QRRecord> list = qrRecordService.findQRRecordList(obj);
            String[] title = {"ID", "业主姓名", "识别时间", "设备名称", "识别位置", "目的楼层", "备注信息"};
            String filename = "QRCodeRecord.xls";
            String sheetName = "sheet1";
            String[][] content = new String[list.size()][7];
            try {
                for (int i = 0; i < list.size(); i++) {
                    content[i][0] = String.valueOf(list.get(i).getRid());
                    content[i][1] = list.get(i).getOwnerName();
                    content[i][2] = list.get(i).getAddTime();
                    content[i][3] = list.get(i).getDeviceName();
                    content[i][4] = list.get(i).getLocation();
                    content[i][5] = String.valueOf(list.get(i).getAimFloor());
                    content[i][6] = list.get(i).getDescription();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            HSSFWorkbook wb = ExcelUtil.getHSSFWorkbook(sheetName, title, content, null);
            try {
                // 响应到客户端
                this.setResponseHeader(response, filename);
                OutputStream os = response.getOutputStream();
                wb.write(os);
                os.flush();
                os.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        /**
         * 向客户端发送响应流方法
         *
         * @param response
         * @param fileName
         */
        public void setResponseHeader(HttpServletResponse response, String fileName) {
            try {
                try {
                    fileName = new String(fileName.getBytes(), "UTF-8");
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                response.setContentType("application/vnd.ms-excel");
                response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }

    4. JS调用

    let url = "localhost:808//.../.../exportExcel?pageStart=0&pageSize=50";
    location.href = url;

    5. 成功后,即通过浏览器进行下载

      此

      处

      留

      白

  • 相关阅读:
    Flutter | 如何优雅的解决依赖版本冲突
    Flutter包依赖冲突解决方法
    Cannot run with sound null safety because dependencies don't support null safety
    软件工程实践2019第三次作业
    【题解】洛谷 P3704 [SDOI2017]数字表格
    关于学历和素质成正比的隐晦思考
    斐波那契数列通项公式
    某不知名比赛游记
    CCPC-final 2020 北京游记
    EC-final 2020-2021 西安游记
  • 原文地址:https://www.cnblogs.com/xfc-exclave/p/10911617.html
Copyright © 2020-2023  润新知