springboot导出excel

1:引入依赖<dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>3.17</version>
        </dependency>
2:建一个ExportExcelUtils类
3:在Controller写方法

 @RequestMapping("/excel")
    @ResponseBody
    public void excel(HttpServletResponse response) throws Exception {

        ExcelData data = new ExcelData();
        data.setName("detail");
        List<String> titles = new ArrayList();
        titles.add("进件时间");
        titles.add("进件类型");
        titles.add("进件总数");
        titles.add("进件通过量");
        titles.add("进件通过率");
        data.setTitles(titles);

        List<List<Object>> rows = new ArrayList();

        Long merchantId = getMerchantId();






        List<RiskApplyVo> result = new ArrayList<>();
        List<Map<String, Object>> list=SlpOrderService.statics(merchantId,"12","20180326","20180416");
        Iterator<Map<String, Object>> iterator = list.iterator();
        while (iterator.hasNext()){
            boolean isExit = false;
            Map<String, Object> next = iterator.next();

            String sysDate = String.valueOf(next.get("sysDate"));
            String version = String.valueOf(next.get("version"));
            String res = String.valueOf(next.get("result"));
            int count = ((Long) next.get("count")).intValue();
            if (version.contains("fd")){
                version = "复贷";
            }else {
                version = "首贷";
            }

            for (RiskApplyVo vo:result){
                if (sysDate.equals(vo.getSysDate())&&version.equals(vo.getType())){
                    if ("APPROVE".equals(res)){
                        vo.setApprove(vo.getApprove()+count);
                    }
                    vo.setCount(vo.getCount()+count);
                    isExit=true;
                    break;
                }
            }
            if (!isExit){
                RiskApplyVo riskApplyVo = new RiskApplyVo();
                riskApplyVo.setSysDate(sysDate);
                riskApplyVo.setType(version);
                if ("APPROVE".equals(res)){
                    riskApplyVo.setApprove(count);
                }
                riskApplyVo.setCount(count);
                result.add(riskApplyVo);

            }


        }
        for (RiskApplyVo vo:result){
            List<Object> row = new ArrayList();
            if (vo.getApprove()==0){
                vo.setApproveRate(0);
            }else {
                vo.setApproveRate(new BigDecimal(vo.getApprove()).divide(new BigDecimal(vo.getCount()),8, RoundingMode.HALF_UP).doubleValue());
            }
            row.add(vo.getSysDate());
            row.add(vo.getType());
            row.add(vo.getCount());
            row.add(vo.getApprove());
            row.add(vo.getApproveRate());
            rows.add(row);
        }


        data.setRows(rows);





        //生成本地
        /*File f = new File("c:/test.xlsx");
        FileOutputStream out = new FileOutputStream(f);
        ExportExcelUtils.exportExcel(data, out);
        out.close();*/

        ExportExcelUtils.exportExcel(response,"detail.xlsx",data);
    }
package com.shilupan.panbao.merchant.web.util;

import com.shilupan.panbao.merchant.data.entity.ExcelData;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFColor;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.Color;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.List;

public class ExportExcelUtils {


    public static void exportExcel(HttpServletResponse response, String fileName, ExcelData data) throws Exception{
        // 告诉浏览器用什么软件可以打开此文件
        response.setHeader("content-Type", "application/vnd.ms-excel");
        // 下载文件的默认名称
        response.setHeader("Content-Disposition", "attachment;filename="+ URLEncoder.encode(fileName, "utf-8"));
        exportExcel(data, response.getOutputStream());
    }

    public static void exportExcel(ExcelData data, OutputStream out) throws Exception {

        XSSFWorkbook wb = new XSSFWorkbook();
        try {
            String sheetName = data.getName();
            if (null == sheetName) {
                sheetName = "Sheet1";
            }
            XSSFSheet sheet = wb.createSheet(sheetName);
            writeExcel(wb,sheet,data);

            wb.write(out);
        } finally {
            wb.close();
        }
    }

    private static void writeExcel(XSSFWorkbook wb, Sheet sheet, ExcelData data) {

        int rowIndex = 0;

        rowIndex = writeTitlesToExcel(wb, sheet, data.getTitles());
        writeRowsToExcel(wb, sheet, data.getRows(), rowIndex);
        autoSizeColumns(sheet, data.getTitles().size() + 1);

    }

    private static int writeTitlesToExcel(XSSFWorkbook wb, Sheet sheet, List<String> titles) {
        int rowIndex = 0;
        int colIndex = 0;
    //字体
        Font titleFont = wb.createFont();
        titleFont.setFontName("simsun");
        titleFont.setBold(true);
        // titleFont.setFontHeightInPoints((short) 14);
        titleFont.setColor(IndexedColors.BLACK.index);

        XSSFCellStyle titleStyle = wb.createCellStyle();
      /*  titleStyle.setAlignment(XSSFCellStyle.ALIGN_CENTER);
        titleStyle.setVerticalAlignment(XSSFCellStyle.VERTICAL_CENTER);
        titleStyle.setFillForegroundColor(new XSSFColor(new Color(182, 184, 192)));
        titleStyle.setFillPattern(XSSFCellStyle.SOLID_FOREGROUND);*/
        titleStyle.setFont(titleFont);
        setBorder(titleStyle, BorderStyle.THIN, new XSSFColor(new Color(0, 0, 0)));
        Row titleRow;

             titleRow = sheet.createRow(rowIndex);




        // titleRow.setHeightInPoints(25);
        colIndex = 0;

        for (String field : titles) {
            Cell cell = titleRow.createCell(colIndex);
            cell.setCellValue(field);
            cell.setCellStyle(titleStyle);
            colIndex++;
        }

        rowIndex++;
        return rowIndex;
    }

    private static int writeRowsToExcel(XSSFWorkbook wb, Sheet sheet, List<List<Object>> rows, int rowIndex) {
        int colIndex = 0;

        Font dataFont = wb.createFont();
        dataFont.setFontName("simsun");
        // dataFont.setFontHeightInPoints((short) 14);
        dataFont.setColor(IndexedColors.BLACK.index);

        XSSFCellStyle dataStyle = wb.createCellStyle();
      /*  dataStyle.setAlignment(XSSFCellStyle.ALIGN_CENTER);
        dataStyle.setVerticalAlignment(XSSFCellStyle.VERTICAL_CENTER);*/
        dataStyle.setFont(dataFont);
        setBorder(dataStyle, BorderStyle.THIN, new XSSFColor(new Color(0, 0, 0)));

        for (List<Object> rowData : rows) {
            Row dataRow = sheet.createRow(rowIndex);
           //dataRow.setHeightInPoints(25);
            colIndex = 0;

            for (Object cellData : rowData) {
                Cell cell = dataRow.createCell(colIndex);
                if (cellData != null) {
                    cell.setCellValue(cellData.toString());
                } else {
                    cell.setCellValue("");
                }

                cell.setCellStyle(dataStyle);
                colIndex++;
            }
            rowIndex++;
        }
        return rowIndex;
    }

    private static void autoSizeColumns(Sheet sheet, int columnNumber) {

        for (int i = 0; i < columnNumber; i++) {
            int orgWidth = sheet.getColumnWidth(i);
            sheet.autoSizeColumn(i, true);
            int newWidth = (int) (sheet.getColumnWidth(i) + 100);
            if (newWidth > orgWidth) {
                sheet.setColumnWidth(i, newWidth);
            } else {
                sheet.setColumnWidth(i, orgWidth);
            }
        }
    }

    private static void setBorder(XSSFCellStyle style, BorderStyle border, XSSFColor color) {
        style.setBorderTop(border);
        style.setBorderLeft(border);
        style.setBorderRight(border);
        style.setBorderBottom(border);
/*        style.setBorderColor(BorderSide.TOP, color);
        style.setBorderColor(BorderSide.LEFT, color);
        style.setBorderColor(BorderSide.RIGHT, color);
        style.setBorderColor(BorderSide.BOTTOM, color);*/
    }
}

已标记关键词 清除标记
©️2020 CSDN 皮肤主题: 书香水墨 设计师:CSDN官方博客 返回首页