JAVA使用poi導出EXCEL

前端:如果你使用的是ajax類型的跨域導出,則無法出現彈框,所以直接選擇window.location.href,具體操作看代碼

後端:上面的地址爲圖片中的地址,如圖

@GetMapping(value = "/export")
    public void exportSysTest(HttpServletRequest request, HttpServletResponse response) {
        try {
            List<Map<String,Object>> rows = sysTestService.selectRows();
            String [][] columnNames = {
                    {"序號","名字","手機號碼","地址","性別","說明"},   {"ID","NAME","MOBILE","ADDRESS","SEX","EXPLAIN"}};
            String [] columnWidth ={"5","20","20","20","20","20"};
            String excelName = "測試管理";
            HSSFWorkbook wb = ExportExcelUtil.createSXSSFWorkbook(columnNames,columnWidth, rows, excelName);
            OutputStream ouputStream = response.getOutputStream();
            response.reset();
            response.setHeader("Content-disposition", "attachment;filename=book.xls");
            response.setContentType("application/octet-stream; charset=utf-8");
            wb.write(ouputStream);
            ouputStream.flush();
            ouputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
}

Excel工具類:

package com.brilliance.core.utils;

import java.util.List;
import java.util.Map;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFFont;
import org.apache.poi.xssf.usermodel.XSSFSheet;

/**
 * 導出到excel表工具
 * wuzk
 * 2020-04-25
 */

public class ExportExcelUtil  {


    public ExportExcelUtil() {
        super();
    }

    public static HSSFWorkbook createSXSSFWorkbook(String[][] columnNames, String[] columnWidth, List<Map<String, Object>> rows, String excelName){
        HSSFWorkbook workbook = new HSSFWorkbook(); // 創建工作薄,相當於一個文件

        Sheet sheet = workbook.createSheet(); // 創建一個表
        //sheet.setDefaultColumnWidth((short) 3); // 設置默認列寬
        //sheet.setColumnWidth(0, 18 * 256); // 設置單位列列寬

        sheet.setMargin(XSSFSheet.TopMargin, 0.64); // 頁邊距(上)
        sheet.setMargin(XSSFSheet.BottomMargin, 0.64); // 頁邊距(下)
        sheet.setMargin(XSSFSheet.LeftMargin, 0.64); // 頁邊距(左)
        sheet.setMargin(XSSFSheet.RightMargin, 0.64); // 頁邊距(右)

        PrintSetup ps = sheet.getPrintSetup();
        ps.setPaperSize(PrintSetup.A4_PAPERSIZE); // 設置紙張大小
        ps.setLandscape(true); // 打印方向,true:橫向,false:縱向(默認)

        // 標題樣式
        CellStyle titleStyle = workbook.createCellStyle();
        titleStyle.setAlignment(HorizontalAlignment.CENTER); // 水平居中
        titleStyle.setVerticalAlignment(VerticalAlignment.CENTER); // 垂直居中
        // 標題字體
        Font titleFont = workbook.createFont();
        titleFont.setFontHeightInPoints((short) 12); // 字體大小
        titleFont.setFontName("宋體");
        titleStyle.setFont(titleFont);

        // 填報單位的樣式
        CellStyle titleStyle_2 = workbook.createCellStyle();
        titleStyle_2.setAlignment(HorizontalAlignment.RIGHT); // 水平居右
        titleStyle_2.setVerticalAlignment(VerticalAlignment.CENTER); // 垂直居中
        // 標題字體
        Font titleFont_2 = workbook.createFont();
        titleFont_2.setFontHeightInPoints((short) 11);
        titleFont_2.setFontName("宋體");
        titleStyle_2.setFont(titleFont_2);

        // 填報單位的樣式
        CellStyle titleStyle_u = workbook.createCellStyle();
        titleStyle_u.setAlignment(HorizontalAlignment.LEFT); // 水平居左
        titleStyle_u.setVerticalAlignment(VerticalAlignment.CENTER); // 垂直居中
        // 標題字體
        Font titleFont_u = workbook.createFont();
        titleFont_u.setUnderline(XSSFFont.U_SINGLE);
        titleFont_u.setFontHeightInPoints((short) 11);
        titleFont_u.setFontName("宋體");
        titleStyle_u.setFont(titleFont_u);

        // 表頭樣式
        CellStyle headerStyle = workbook.createCellStyle();
        headerStyle.setAlignment(HorizontalAlignment.CENTER); // 水平居中
        headerStyle.setVerticalAlignment(VerticalAlignment.CENTER); // 垂直居中
        headerStyle.setBorderBottom(BorderStyle.THIN); // 下邊框
        headerStyle.setBorderLeft(BorderStyle.THIN); // 左邊框
        headerStyle.setBorderTop(BorderStyle.THIN); // 上邊框
        headerStyle.setBorderRight(BorderStyle.THIN); // 右邊框
        headerStyle.setWrapText(true); // 設置多行顯示
        //這兩句話是表示將表頭單元格格式設置爲文本型,在後面只要調用-----.setDataFormat(format.getFormat("@"))的方法就可以將數據設置爲文本型。
        DataFormat format = workbook.createDataFormat();
        headerStyle.setDataFormat(format.getFormat("@"));
        // 表頭字體
        Font headerFont = workbook.createFont();
        headerFont.setFontHeightInPoints((short) 9);
        headerFont.setFontName("宋體");
        headerStyle.setFont(headerFont);

        // 數據樣式
        CellStyle dataStyle = workbook.createCellStyle();
        dataStyle.setAlignment(HorizontalAlignment.CENTER); // 水平居中
        dataStyle.setVerticalAlignment(VerticalAlignment.CENTER); // 垂直居中
        dataStyle.setBorderBottom(BorderStyle.THIN); // 下邊框
        dataStyle.setBorderLeft(BorderStyle.THIN); // 左邊框
        dataStyle.setBorderTop(BorderStyle.THIN); // 上邊框
        dataStyle.setBorderRight(BorderStyle.THIN); // 右邊框
        dataStyle.setDataFormat(format.getFormat("@"));      //將數據單元格格式設置爲文本類型
        // 數據字體
        Font dataFont = workbook.createFont();
        dataFont.setFontHeightInPoints((short) 9);
        dataFont.setFontName("宋體");
        dataStyle.setFont(dataFont);

        // 尾部樣式
        CellStyle footStyle = workbook.createCellStyle();
        footStyle.setAlignment(HorizontalAlignment.CENTER); // 水平居中
        footStyle.setVerticalAlignment(VerticalAlignment.CENTER); // 垂直居中
        // 尾部字體
        Font footFont = workbook.createFont();
        footFont.setFontHeightInPoints((short) 11);
        footFont.setFontName("宋體");
        footStyle.setFont(footFont);

        CellStyle commonStyle = workbook.createCellStyle();
        commonStyle.setBorderBottom(BorderStyle.THIN); // 下邊框
        commonStyle.setBorderLeft(BorderStyle.THIN); // 左邊框
        commonStyle.setBorderTop(BorderStyle.THIN); // 上邊框
        commonStyle.setBorderRight(BorderStyle.THIN); // 右邊框

        // 表格標題行
        Row row0 = sheet.createRow(0);
        row0.setHeight((short)(3 * 256));
        Cell cell0_0 = row0.createCell(0); // 創建單元格,參數說明的是第幾個單元格
        cell0_0.setCellStyle(titleStyle);
        cell0_0.setCellValue(excelName); // 設置單元格 和裏面的內容

        if(columnWidth.length>0){
            Integer clWidth;
            for(int i =0;i<columnWidth.length;i++){
                if(columnWidth[i]!=null &&!"".equals(columnWidth[i])){
                    clWidth = Integer.valueOf(columnWidth[i]);
                    sheet.setColumnWidth(i, clWidth*256);
                }
            }
        }



        Row row = null;
        Cell cell = null;
        for(int i = 1 ; i<=columnNames.length ; i++){
            row = sheet.createRow(i);
            row.setHeight((short)(2 * 256));
            for(int j = 0 ;j < columnNames[i-1].length;j++){
                cell = row.createCell(j);
                cell.setCellValue(columnNames[i-1][j]);
                cell.setCellStyle(headerStyle);

            }
        }

        sheet.getRow(columnNames.length).setZeroHeight(true);
        // 合併單元格
        sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, columnNames[0].length-1)); // 合併大標題行
        String[] names = columnNames[columnNames.length-1];

        // 數據填充,標題佔一行,columnNames佔columnNames.length行,之後纔到數據行
        Object obj = null;

        for (int i = 0; i < rows.size(); i++) {
            Row dataRow = sheet.createRow(columnNames.length+1+ i);
            Map<String,Object> project = rows.get(i);
            for (int j = 0; j <names.length; j++) {
                Cell dataCell = dataRow.createCell(j);
                dataCell.setCellStyle(dataStyle);
                obj = project.get(names[j]);
                dataCell.setCellValue(obj==null?"":obj.toString());
            }
        }

        return workbook;
    }
}

頁面原圖:

點擊導出:

Excel:

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章