文件导出成excel

一、前端代码

 // 批量导出
    toExport: function(){
        //判断选中状态
        var ids ="";
        var num = 0;

        $(".checkbox").each(function () {
            if($(this).is(':checked')){
                ids +=$(this).val() + ",";
                num++;
            }
        });
        if(num <=0 ){
            toastr.error('请选择需要导出的记录!');
            return;
        }
        ids = ids.slice(0,ids.length-1);
        // 拼接前端的form表单
        var tempForm = $('<form style="display:none;" id="tempFor" method="post" target="_blank" action="'+backbasePath+'/apia/v1/exportFile">' +
            '<input type="hidden" id="id" name="id" value="'+ids+'"/>' +
            '<input type="hidden" id="token" name="token" value="'+$("#token").val()+'"/></form>');
        // 将拼接的form表单加在body里面
        $('body').append(tempForm);
        //表单提交,调用后端的控制器
        tempForm.submit();
        //表单删除
        tempForm.remove();
    }

二、后端代码

    // 批量导出
    @RequestMapping(value = "/exportFile")
    public void exportFile(HttpServletRequest request,HttpServletResponse response)  {
        // 根据id获取到列表中的数据信息
        List<LinkedHashMap<String,Object>> dataList = null;
        try {
            dataList = healthService.getEmpById(request);
        } catch (Exception e) {
            e.printStackTrace();
        }
        // excel中的表格头数据
        List<String> head = new ArrayList<>();
     // 导出的表头自己定义 head.add(
"姓名"); String sheetName = "XXXX表"; String fileName = "XXXX表.xls"; try { ImportsExcel.exportExcel(response, head, dataList,sheetName, fileName, 20,11); } catch (IOException e) { e.printStackTrace(); } }
 /**
     * Excel表格导出
     * @param response HttpServletResponse对象
     * @param head List<String> 表头数据集合
     * @param excelData Excel表格的数据,封装为List<LinkedHashMap<String,Object>>
     * @param sheetName sheet的名字
     * @param fileName 导出Excel的文件名
     * @param columnWidth Excel表格的宽度,建议为15  number 合并单元格的个数
     * @throws IOException 抛IO异常
     */
    public static void exportExcel(HttpServletResponse response,List<String> head,  List<LinkedHashMap<String,Object>> excelData, String sheetName,
                                   String fileName, int columnWidth, int number) throws IOException {

        //声明一个工作簿
        HSSFWorkbook workbook = new HSSFWorkbook();
        //生成一个表格,设置表格名称
        HSSFSheet sheet = workbook.createSheet(sheetName);
        //设置表格列宽度
        sheet.setDefaultColumnWidth(columnWidth);
        // 设置垂直居中
        sheet.setVerticallyCenter(true);

        //标题样式
        HSSFCellStyle styleMain = workbook.createCellStyle();
        //水平居中
        styleMain.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        //垂直居中
        styleMain.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
        // 设置标题字体
        HSSFFont font = workbook.createFont();
        font.setFontName("黑体");
        //设置字体大小
        font.setFontHeightInPoints((short) 16);
        styleMain.setFont(font);

        // 表头样式
        HSSFCellStyle headStyle = workbook.createCellStyle();
        //水平居中
        headStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        //垂直居中
        headStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
        // 字体
        HSSFFont headFont = workbook.createFont();
        headFont.setFontName("仿宋_GB2312");
        headFont.setFontHeightInPoints((short) 12);
        //粗体显示
        headFont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
        headStyle.setFont(headFont);

        // 内容样式
        HSSFCellStyle contentStyle = workbook.createCellStyle();
        //水平居中
        headStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        //垂直居中
        headStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
        // 字体
        HSSFFont contentFont = workbook.createFont();
        contentFont.setFontName("仿宋_GB2312");
        contentFont.setFontHeightInPoints((short) 12);
        contentStyle.setFont(contentFont);

        //创建第一行
        HSSFRow titleRow = sheet.createRow(0);
        //创建单元格(excel的单元格,参数为列索引,可以是0~255之间的任何一个
        HSSFCell titleCell=titleRow.createCell(0);
        //设置单元格内容
        titleCell.setCellValue(sheetName);
        titleCell.setCellStyle(styleMain);
        ///合并单元格CellRangeAddress构造参数依次表示起始行,截至行,起始列,截至列
        sheet.addMergedRegion(new CellRangeAddress(0,0,0,number));

        //创建表头
        HSSFRow headRow = sheet.createRow(1);
        //遍历添加表头
        for (int i = 0; i < head.size(); i++) {
            //创建一个单元格
            HSSFCell cell = headRow.createCell(i);
            //创建一个内容对象
            HSSFRichTextString text = new HSSFRichTextString(head.get(i));
            //将内容对象的文字内容写入到单元格中
            cell.setCellValue(text);
            cell.setCellStyle(headStyle);
        }
        //写入 List<Map<String, Object>>中的数据
        // 标题,表头,从第三行开始添加数据
        int rowIndex = 2;
        for (int i = 0; i < excelData.size(); i++) {
            //创建一个row行,然后自增1
            HSSFRow row = sheet.createRow(rowIndex++);
            Map<String, Object> map = excelData.get(i);
            Iterator iterator = map.keySet().iterator();
            int num=0;
            while (iterator.hasNext()) {
                //创建一个单元格
                HSSFCell cell = row.createCell(num);
                String string = (String) iterator.next();
                //创建一个内容对象
                HSSFRichTextString text = new HSSFRichTextString((String)map.get(string));
                //将内容对象的文字内容写入到单元格中
                cell.setCellValue(text);
                cell.setCellStyle(contentStyle);
                // 添加具体的循环字符
                if(num <map.size()){
                    num++;
                }
            }
        }
        //准备将Excel的输出流通过response输出到页面下载
        response.setContentType("application/octet-stream");
        //设置导出Excel的名称
        response.setHeader("Content-disposition", "attachment;filename="+ java.net.URLEncoder.encode(fileName,"UTF-8"));
        //刷新缓冲
        response.flushBuffer();
        //workbook将Excel写入到response的输出流中,供页面下载该Excel文件
        workbook.write(response.getOutputStream());
    }
    

猜你喜欢

转载自www.cnblogs.com/flyShare/p/12498518.html