SpringBoot中Excel的导出

导出使用的工具类

import com.netinfo.emp.record.web.entity.ExcelData;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;

/**
 * Created by zzq on 2019/05/09.
 */
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();
            out.close();
        }
    }

    private static void writeExcel(XSSFWorkbook wb, Sheet sheet, ExcelData data) {
        int 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, Map 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.setFont(titleFont);
        setBorder(titleStyle, BorderStyle.THIN);

        Row titleRow = sheet.createRow(rowIndex);
        // titleRow.setHeightInPoints(25);

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

        rowIndex++;
        return rowIndex;
    }

    private static int writeRowsToExcel(XSSFWorkbook wb, Sheet sheet, List> 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.setFont(dataFont);
        setBorder(dataStyle, BorderStyle.THIN);

        for (List 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) {
        style.setBorderTop(border);
        style.setBorderLeft(border);
        style.setBorderRight(border);
        style.setBorderBottom(border);
    } 
  

 

使用类

 

/**
 * 导出列表数据到excel
 * @param response
 * @param queryId
 * @param pageIndex
 * @param pageSize
 * @return
 */
public WebReturn exportRecord(HttpServletResponse response, String queryId, Integer pageIndex, Integer pageSize) {
    WebReturn webReturn = new WebReturn();
    try {
        //
        webReturn = queryRecord2(queryId, pageIndex, pageSize);
        if (!webReturn.isResult()) {
            log.error(String.format("exportRecord -mediaQuery fail. [%d]%s", webReturn.getCode(), webReturn.getMsg()));
            return webReturn;
        }
        WebReturn webReturn1 = viewColumnService.getColumns("9112610110100000000", "2", "1");
        if (!webReturn1.isResult()) {
            log.error(String.format("exportRecord -getColumns fail. [%d]%s", webReturn1.getCode(), webReturn1.getMsg()));
            return webReturn1;
        }
        //

        //
        ExcelData data = new ExcelData();
        data.setName("数据列表");
        Map titles = new LinkedHashMap<>();
        List viewColumns = (List)webReturn1.getData();
        for (ViewColumn column : viewColumns){
            if (column.getViewOnPage() == 1){
                titles.put(column.getColId(), column.getDisplay());
            }
        }
        data.setTitles(titles);
        //

        //
        List> mediaList = (List>)webReturn.getData();
        List> rows = new ArrayList();
        List row;
        for (Map media : mediaList){
            row = new ArrayList();
            if (titles.get("9122610110100000001") != null) row.add(media.get("agent_id"));
            if (titles.get("9122610110100000002") != null) row.add(media.get("media_id"));
            if (titles.get("9122610110100000003") != null) row.add(media.get("passageway"));
            if (titles.get("9122610110100000004") != null) row.add(media.get("extension"));
            if (titles.get("9122610110100000005") != null) row.add(media.get("start_time"));
            if (titles.get("9122610110100000006") != null) row.add(media.get("end_time"));
            if (titles.get("9122610110100000007") != null) row.add(media.get("last_time"));
            if (titles.get("9122610110100000008") != null) {
                if ("".equals(media.get("call_direction")) || media.get("call_direction") == null){
                    row.add("");
                }else {
                    row.add("73".equals(media.get("call_direction")) ? "呼入" : "呼出");
                }
            }
            if (titles.get("9122610110100000009") != null) row.add(media.get("call_id"));
            if (titles.get("9122610110100000010") != null) row.add(media.get("skill_queue"));
            if (titles.get("9122610110100000011") != null) row.add(media.get("caller"));
            if (titles.get("9122610110100000012") != null) row.add(media.get("callee"));
            rows.add(row);
        }

        data.setRows(rows);
        //

        ExportExcelUtils.exportExcel(response, "数据.xlsx", data);
    }catch (Exception ex){
        log.error(String.format("exportRecord fail. %s", ex.getMessage()));
        ex.printStackTrace();
        webReturn.setResult(false);
        webReturn.setCode(Defines.RET_FAIL);
        webReturn.setMsg(Defines.MSG_SERVER_ERROR);
    }
    return webReturn;
} 
  

                            
                        
                    
                    
                    

你可能感兴趣的:(SpringBoot中Excel的导出)