POI 3.17 導出Excel,基礎代碼

工作中經常要用到excel的導出,所以參考其他人的demo寫了一個導出excel的基礎代碼。如果以後再需要用的時候,直接拿來修改下就能直接使用。

參考博文地址:https://blog.csdn.net/phil_jing/article/details/78307819

以下是maven依賴

        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>3.17</version>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>3.17</version>
        </dependency>

工具包

        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>3.9</version>
        </dependency>

以下是導出代碼實現

package com.example.demo.utils;

import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.commons.lang3.time.FastDateFormat;
import java.util.Collection;
import java.util.Date;
import java.util.Iterator;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.FillPatternType;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.VerticalAlignment;
import org.apache.poi.ss.usermodel.Workbook;

public class ExportExcel {

    /**
     * excel導出
     * @param sheetName sheet名稱
     * @param title 標題
     * @param headers 表頭
     * @param columns 字段名稱
     * @param dataset 數據集合
     * @param pattern 日期格式
     * @return Workbook
     */
    public static Workbook exportExcel(String sheetName, String title, String[] headers, String[] columns,
                                           Collection<Map<String, Object>> dataset, String pattern){

        // 創建excel工作簿
        Workbook workbook = new XSSFWorkbook();
        // 創建第一個sheet(頁),並命名
        Sheet sheet = workbook.createSheet(sheetName);

        // -----------------表格標題行樣式-----------------
        CellStyle titleStyle = workbook.createCellStyle();
        // 設置這些樣式
        titleStyle.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex()); // 填充顏色
        titleStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND); // 填充樣式
        titleStyle.setAlignment(HorizontalAlignment.CENTER); // 水平居中
        titleStyle.setVerticalAlignment(VerticalAlignment.CENTER); //垂直居中
        titleStyle.setBorderBottom(BorderStyle.THIN);
        titleStyle.setBorderLeft(BorderStyle.THIN);
        titleStyle.setBorderRight(BorderStyle.THIN);
        titleStyle.setBorderTop(BorderStyle.THIN);
        // 生成一個字體
        Font font = workbook.createFont();
        font.setColor(IndexedColors.WHITE.getIndex());
        font.setFontHeightInPoints((short) 12);
        font.setBold(true);
        // font.setBoldweight((short)700));
        // 把字體應用到當前的樣式
        titleStyle.setFont(font);

        // ----------------樣式2 內容的背景----------------
        CellStyle style2 = workbook.createCellStyle();
        style2.setFillForegroundColor(IndexedColors.WHITE.getIndex());
        style2.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        style2.setBorderBottom(BorderStyle.THIN);
        style2.setBorderLeft(BorderStyle.THIN);
        style2.setBorderRight(BorderStyle.THIN);
        style2.setBorderTop(BorderStyle.THIN);
        style2.setAlignment(HorizontalAlignment.CENTER);
        style2.setVerticalAlignment(VerticalAlignment.CENTER);
        // 生成另一個字體
        Font font2 = workbook.createFont();
        font.setBold(true);
        // font2.setBoldweight(HSSFFont.BOLDWEIGHT_NORMAL);
        // 把字體應用到當前的樣式
        style2.setFont(font2);

        int rowCount = 0; // 起始行號
        Row row;
        // ------------設置首行標題標題--------------
        if (StringUtils.isNotEmpty(title)){
            // 如果有標題
            row = sheet.createRow(rowCount);
            Cell cell = row.createCell(rowCount);
            cell.setCellValue(title);
            cell.setCellStyle(titleStyle);
            //合併單元格
            CellRangeAddress region = new CellRangeAddress(rowCount, rowCount, 0, headers.length-1);
            sheet.addMergedRegion(region);
            rowCount++;
        }

        // ----------------表頭------------------
        row = sheet.createRow(rowCount);
        //
        for (int i = 0; i < headers.length; i++) {
            Cell cell = row.createCell(i);
            cell.setCellStyle(titleStyle);
            // 富文本字符串:用於同一單元格內容展示不用樣式
            // RichTextString text = new XSSFRichTextString(headers[i]);
            cell.setCellValue(headers[i]);
        }
        rowCount++;

        // --------------單元格數據----------------
        if(StringUtils.isEmpty(pattern)) {
            pattern = "yyyy/MM/dd";
        }
        FastDateFormat instance = FastDateFormat.getInstance(pattern);
        // 遍歷集合數據,產生數據行
        Iterator<Map<String, Object>> it = dataset.iterator(); // 多個Map集合
        int count = 0;
        while (it.hasNext()) {
            row = sheet.createRow(rowCount);
            Map<String, Object> map = it.next();
            count = headers.length < columns.length ? headers.length : columns.length;
            for (int i = 0; i < count; i++) {
                Cell cell = row.createCell(i);
                cell.setCellStyle(style2);
                try {
                    Object value = map.get(columns[i]);
                    // 判斷值的類型後進行強制類型轉換
                    String textValue = null;
                    if (value instanceof Date) {
                        Date date = (Date) value;
                        textValue = instance.format(date);
                    }else {
                        // 其它數據類型都當作字符串簡單處理
                        if (value != null) {
                            textValue = value.toString();
                        } else {
                            textValue = "";
                        }
                    }
                    // 利用正則表達式判斷textValue是否全部由數字組成
                    if (textValue != null) {
                        Pattern p = Pattern.compile("^//d+(//.//d+)?$");
                        Matcher matcher = p.matcher(textValue);
                        if (matcher.matches()) {
                            // 是數字當作double處理
                            cell.setCellValue(Double.parseDouble(textValue));
                        } else {
                            cell.setCellValue(textValue);
                            cell.setCellStyle(style2);
                        }
                    }
                } catch (SecurityException e) {
                    e.printStackTrace();
                }
            }
            rowCount++;
        }
        return workbook;
    }
}

控制層調用

package com.example.demo.controller;

import com.example.demo.model.Bean;
import com.example.demo.utils.ExportExcel;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.time.LocalTime;
import java.util.*;

@RestController
public class TestController {

    private static String EXPORT_XLSX_FILE_SUFFIX = ".xlsx";
    private static String EXPORT_XLS_FILE_SUFFIX = ".xls";

    /**
     * 導出
     */
    @RequestMapping(value = "/export")
    public void getExcel1(@RequestParam Map<String, Object> map, HttpServletResponse response) throws Exception {
        LocalTime localTime1 = LocalTime.now();
        System.out.println("開始時間:" + localTime1);
        //查詢條件
        System.out.println((String) map.get("name"));
        //
        List<Bean> beanList = new ArrayList<>();
        for (int i = 0; i<10000; i++){
            Bean bean1 = new Bean();
            bean1.setAttribute("屬性" + i);
            bean1.setName("字段" + i);
            bean1.setLength(i);
            bean1.setType("類型" + i);
            bean1.setNote("註釋" + i);
            beanList.add(bean1);
        }
        List<Map<String,Object>> list = new ArrayList<>();
        for (Bean bean : beanList) {
            Map<String,Object> hashMap = new HashMap<>();
            //
            hashMap.put("attribute",bean.getAttribute());
            hashMap.put("name",bean.getName());
            hashMap.put("length",bean.getLength());
            hashMap.put("type",bean.getType());
            hashMap.put("note",bean.getNote());
            //
            list.add(hashMap);
        }

        String sheetName = "sheet1";
        String title1 = "標題"; // 標題
        String[] title2 = {"屬性", "字段", "長度","類型","註釋"}; // 表頭
        String[] columns = {"attribute", "name", "length","type","note"}; // 字段
        String pattern = "yyyy/MM/dd"; // 日期格式
        //
        String excelType;
        if(StringUtils.isEmpty(map.get("excel_type"))) {
            excelType = EXPORT_XLSX_FILE_SUFFIX;
        } else {
            excelType = (String) map.get("excel_type");
        }
        Workbook workbook = ExportExcel.exportExcel(sheetName,title1,title2,columns,list,pattern);
        response.setHeader("Content-type", "application/vnd.ms-excel");
        response.setCharacterEncoding("UTF-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + System.currentTimeMillis() + excelType);
        workbook.write(response.getOutputStream());
        workbook.close();
        //
        LocalTime localTime2 = LocalTime.now();
        System.out.println("結束時間:" + localTime2);
    }

}

項目啓動後,在瀏覽器地址欄輸入:localhost:8080/export?excel_type=.xls&name=小明

導出1w條數據所用時間大概爲3-4秒

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