一個Excel工具類

原文鏈接:https://blog.csdn.net/Lining_s/article/details/87923028

在工作中有很多場景需要讀取excel,導出excel
搜了是這位大佬寫的excel工具類,
https://blog.csdn.net/l1028386804/article/details/79659605
在工作中遇到了一點問題進行了優化,
主要包括
讀取excel:統一返回二位數組,(日期,數字格式的處理)
導出excel:自適應寬度,科學計數法優化(2003),導出這裏只優化了2003,因爲導出xls格式都可以打開

先看效果

在這裏插入圖片描述

測試讀取


     /**
     * 測試讀取excel
     *
     * @throws IOException
     * @throws InvalidFormatException
     */
	@Test
    public void readExcel() throws IOException, InvalidFormatException {
        String excel = "C:\\Users\\chenggaowei\\Desktop\\新建 XLSX 工作表.xlsx";
        String[][] datas = ExcelUtil.readExcel(new File(excel));
        for (String[] data : datas) {
            System.out.println(JSON.toJSONString(data));
        }
    }

	/**
     * 測試導出excel
     *
     * @throws IOException
     */
    @Test
    public void exportExcel() throws IOException {

        List<UserDO> users = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            UserDO userDO = new UserDO();
            userDO.setId(IdUtil.nextId());
            userDO.setUid(IdUtil.uuid());
            userDO.setUserName("測試Excel" + (i + 1));
            users.add(userDO);
        }
        UserDO userDO1 = new UserDO();
        userDO1.setId(IdUtil.nextId());
        userDO1.setUid(IdUtil.uuid());
        users.add(userDO1);
        for (int i = 0; i < 10; i++) {
            UserDO userDO = new UserDO();
            userDO.setId(IdUtil.nextId());
            userDO.setUid(IdUtil.uuid());
            userDO.setUserName("測試Excel" + (i + 1));
            users.add(userDO);
        }

        File file = new File("C:\\Users\\chenggaowei\\Desktop\\測試excel.xls");
        String[] header = new String[]{"編號", "用戶Id", "用戶名"};
        new ExcelUtil().exportExcel("用戶數據", header, users, new FileOutputStream(file));
    }

效果
在這裏插入圖片描述
在這裏插入圖片描述
原文鏈接
https://blog.csdn.net/l1028386804/article/details/79659605

package com.test.utils;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.*;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.Collection;
import java.util.Date;
import java.util.Iterator;
import java.util.Objects;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static org.apache.poi.ss.usermodel.FillPatternType.SOLID_FOREGROUND;
import static org.apache.poi.ss.usermodel.IndexedColors.BLACK;
import static org.apache.poi.ss.usermodel.IndexedColors.LIGHT_CORNFLOWER_BLUE;


/**
 * 導出Excel
 *
 * @param <T>
 * @author liuyazhuang
 */
@Slf4j
public class ExcelUtil<T> {

    // 2007 版本以上 最大支持1048576行
    public final static String EXCEl_FILE_2007 = "2007";
    // 2003 版本 最大支持65536 行
    public final static String EXCEL_FILE_2003 = "2003";

    private static final String NUMBER_REGEX = "^\\d+(\\.\\d+)?$";
    private static final String DATE_FORMAT = "yyyy-MM-dd hh:mm:ss";

    private static final SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT);

    private static final String pattern = "\\d{4}\\.";

    /**
     * <p>
     * 導出帶有頭部標題行的Excel <br>
     * 時間格式默認:yyyy-MM-dd hh:mm:ss <br>
     * </p>
     *
     * @param title   表格標題
     * @param headers 頭部標題集合
     * @param dataset 數據集合
     * @param out     輸出流
     */
    public void exportExcel(String title, String[] headers, Collection<T> dataset, OutputStream out) {
        exportExcel2003(title, headers, dataset, out, DATE_FORMAT);
    }

    /**
     * <p>
     * 導出帶有頭部標題行的Excel <br>
     * 時間格式默認:yyyy-MM-dd hh:mm:ss <br>
     * </p>
     *
     * @param title   表格標題
     * @param headers 頭部標題集合
     * @param dataset 數據集合
     * @param out     輸出流
     * @param version 2003 或者 2007,不傳時默認生成2003版本
     */
    public void exportExcel(String title, String[] headers, Collection<T> dataset, OutputStream
            out, String version) {
        if (StringUtils.isBlank(version) || EXCEL_FILE_2003.equals(version.trim())) {
            exportExcel2003(title, headers, dataset, out, DATE_FORMAT);
        } else {
            exportExcel2007(title, headers, dataset, out, DATE_FORMAT);
        }
    }

    /**
     * <p>
     * 通用Excel導出方法,利用反射機制遍歷對象的所有字段,將數據寫入Excel文件中 <br>
     * 此版本生成2007以上版本的文件 (文件後綴:xlsx)
     * </p>
     *
     * @param title   表格標題名
     * @param headers 表格頭部標題集合
     * @param dataset 需要顯示的數據集合,集合中一定要放置符合JavaBean風格的類的對象。此方法支持的
     *                JavaBean屬性的數據類型有基本數據類型及String,Date
     * @param out     與輸出設備關聯的流對象,可以將EXCEL文檔導出到本地文件或者網絡中
     * @param pattern 如果有時間數據,設定輸出格式。默認爲"yyyy-MM-dd hh:mm:ss"
     */
    @SuppressWarnings({"unchecked", "rawtypes"})
    private void exportExcel2007(String title, String[] headers, Collection<T> dataset,
                                 OutputStream out, String pattern) {
        // 聲明一個工作薄
        XSSFWorkbook workbook = new XSSFWorkbook();
        // 生成一個表格
        XSSFSheet sheet = workbook.createSheet(title);
        // 設置表格默認列寬度爲15個字節
        sheet.setDefaultColumnWidth(20);
        // 生成一個樣式
        XSSFCellStyle style = workbook.createCellStyle();
        // 設置這些樣式
        style.setFillForegroundColor(new XSSFColor(java.awt.Color.gray));
        style.setFillPattern(SOLID_FOREGROUND);
        style.setBorderBottom(BorderStyle.THIN);
        style.setBorderLeft(BorderStyle.THIN);
        style.setBorderRight(BorderStyle.THIN);
        style.setBorderTop(BorderStyle.THIN);
        style.setAlignment(HorizontalAlignment.CENTER);
        // 生成一個字體
        XSSFFont font = workbook.createFont();
        font.setBold(true);
        font.setFontName("宋體");
        font.setColor(new XSSFColor(java.awt.Color.BLACK));
        font.setFontHeightInPoints((short) 11);
        // 把字體應用到當前的樣式
        style.setFont(font);
        // 生成並設置另一個樣式
        XSSFCellStyle style2 = workbook.createCellStyle();
        style2.setFillForegroundColor(new XSSFColor(java.awt.Color.WHITE));
        style2.setFillPattern(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);
        // 生成另一個字體
        // XSSFFont font2 = workbook.createFont();
        // font2.setBold(true);
        // 把字體應用到當前的樣式
        // style2.setFont(font2);

        // 產生表格標題行
        XSSFRow row = sheet.createRow(0);
        XSSFCell cellHeader;
        for (int i = 0; i < headers.length; i++) {
            cellHeader = row.createCell(i);
            cellHeader.setCellStyle(style);
            cellHeader.setCellValue(new XSSFRichTextString(headers[i]));
        }

        // 遍歷集合數據,產生數據行
        Iterator<T> it = dataset.iterator();
        int index = 0;
        T t;
        Field[] fields;
        Field field;
        XSSFRichTextString richString;
        Pattern p = Pattern.compile(NUMBER_REGEX);
        Matcher matcher;
        String fieldName;
        String getMethodName;
        XSSFCell cell;
        Class tCls;
        Method getMethod;
        Object value;
        String textValue;
        SimpleDateFormat sdf = new SimpleDateFormat(pattern);
        while (it.hasNext()) {
            index++;
            row = sheet.createRow(index);
            t = (T) it.next();
            // 利用反射,根據JavaBean屬性的先後順序,動態調用getXxx()方法得到屬性值
            fields = t.getClass().getDeclaredFields();
            for (int i = 0; i < fields.length; i++) {
                cell = row.createCell(i);
                cell.setCellStyle(style2);
                field = fields[i];
                fieldName = field.getName();
                getMethodName = "get" + fieldName.substring(0, 1).toUpperCase()
                        + fieldName.substring(1);
                try {
                    tCls = t.getClass();
                    getMethod = tCls.getMethod(getMethodName, new Class[]{});
                    value = getMethod.invoke(t, new Object[]{});
                    // 判斷值的類型後進行強制類型轉換
                    textValue = null;
                    if (value instanceof Integer) {
                        cell.setCellValue((Integer) value);
                    } else if (value instanceof Float) {
                        textValue = String.valueOf((Float) value);
                        cell.setCellValue(textValue);
                    } else if (value instanceof Double) {
                        textValue = String.valueOf((Double) value);
                        cell.setCellValue(textValue);
                    } else if (value instanceof Long) {
                        cell.setCellValue((Long) value);
                    }
                    if (value instanceof Boolean) {
                        textValue = "是";
                        if (!(Boolean) value) {
                            textValue = "否";
                        }
                    } else if (value instanceof Date) {
                        textValue = sdf.format((Date) value);
                    } else {
                        // 其它數據類型都當作字符串簡單處理
                        if (value != null) {
                            textValue = value.toString();
                        }
                    }
                    if (textValue != null) {
                        matcher = p.matcher(textValue);
                        if (matcher.matches()) {
                            // 是數字當作double處理
                            cell.setCellValue(Double.parseDouble(textValue));
                        } else {
                            richString = new XSSFRichTextString(textValue);
                            cell.setCellValue(richString);
                        }
                    }
                } catch (SecurityException e) {
                    e.printStackTrace();
                } catch (NoSuchMethodException e) {
                    e.printStackTrace();
                } catch (IllegalArgumentException e) {
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                } catch (InvocationTargetException e) {
                    e.printStackTrace();
                } finally {
                    // 清理資源
                }
            }
        }
        try {
            workbook.write(out);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    /**
     * <p>
     * 通用Excel導出方法,利用反射機制遍歷對象的所有字段,將數據寫入Excel文件中 <br>
     * 此方法生成2003版本的excel,文件名後綴:xls <br>
     * </p>
     *
     * @param title   表格標題名
     * @param headers 表格頭部標題集合
     * @param dataset 需要顯示的數據集合,集合中一定要放置符合JavaBean風格的類的對象。此方法支持的
     *                JavaBean屬性的數據類型有基本數據類型及String,Date
     * @param out     與輸出設備關聯的流對象,可以將EXCEL文檔導出到本地文件或者網絡中
     * @param pattern 如果有時間數據,設定輸出格式。默認爲"yyyy-MM-dd hh:mm:ss"
     */
    @SuppressWarnings({"unchecked", "rawtypes"})
    private void exportExcel2003(String title, String[] headers, Collection<T> dataset,
                                 OutputStream out, String pattern) {

        try (HSSFWorkbook workbook = new HSSFWorkbook()) {// 聲明一個工作薄
            // 生成一個表格
            HSSFSheet sheet = workbook.createSheet(title);
            // 生成一個樣式
            HSSFCellStyle style = workbook.createCellStyle();
            // 設置這些樣式
            style.setFillForegroundColor(LIGHT_CORNFLOWER_BLUE.index);
            style.setFillPattern(SOLID_FOREGROUND);
//            style.setBorderBottom(BorderStyle.THIN);
//            style.setBorderLeft(BorderStyle.THIN);
//            style.setBorderRight(BorderStyle.THIN);
//            style.setBorderTop(BorderStyle.THIN);
            style.setAlignment(HorizontalAlignment.CENTER);
            // 生成一個字體
            HSSFFont font = workbook.createFont();
            // font.setBold(true);
            //font.setFontName("宋體");
            font.setColor(BLACK.index);
            font.setFontHeightInPoints((short) 12);
            // 把字體應用到當前的樣式
            style.setFont(font);
            // 生成並設置另一個樣式
            HSSFCellStyle style2 = workbook.createCellStyle();
            HSSFDataFormat format = workbook.createDataFormat();
            style2.setDataFormat(format.getFormat("@"));
            // 生成另一個字體
            // HSSFFont font2 = workbook.createFont();
            // font2.setBold(true);
            // 把字體應用到當前的樣式
            // style2.setFont(font2);

            // 產生表格標題行
            HSSFRow row = sheet.createRow(0);
            HSSFCell cellHeader;
            for (int i = 0; i < headers.length; i++) {
                cellHeader = row.createCell(i);
                cellHeader.setCellStyle(style);
                cellHeader.setCellValue(new HSSFRichTextString(headers[i]));
            }

            // 遍歷集合數據,產生數據行
            Iterator<T> it = dataset.iterator();
            int index = 0;
            T t;
            Field[] fields;
            Field field;
            HSSFRichTextString richString;
            Pattern p = Pattern.compile(NUMBER_REGEX);
            Matcher matcher;
            String fieldName;
            String getMethodName;
            HSSFCell cell;
            Class tCls;
            Method getMethod;
            Object value;
            String textValue;
            SimpleDateFormat sdf = new SimpleDateFormat(pattern);

            while (it.hasNext()) {
                index++;
                row = sheet.createRow(index);
                t = it.next();
                // 利用反射,根據JavaBean屬性的先後順序,動態調用getXxx()方法得到屬性值
                fields = t.getClass().getDeclaredFields();
                for (int i = 0; i < fields.length; i++) {
                    cell = row.createCell(i);
                    cell.setCellStyle(style2);
                    field = fields[i];
                    fieldName = field.getName();
                    getMethodName = "get" + fieldName.substring(0, 1).toUpperCase()
                            + fieldName.substring(1);
                    try {
                        tCls = t.getClass();
                        getMethod = tCls.getMethod(getMethodName, new Class[]{});
                        value = getMethod.invoke(t, new Object[]{});
                        if (value instanceof LocalDateTime) {
                            textValue = DateUtil.format((LocalDateTime) value, DATE_FORMAT);
                        } else {
                            if (Objects.isNull(value)) {
                                value = "";
                            }
                            textValue = value.toString();
                        }
                        cell.setCellValue(textValue);
                        sheet.setColumnWidth(i, (value.toString().length() + 2) * 256);
                    } catch (SecurityException e) {
                        log.error("SecurityException {}", e);
                    } catch (NoSuchMethodException e) {
                        log.error("NoSuchMethodException {}", e);
                    } catch (IllegalArgumentException e) {
                        log.error("IllegalArgumentException {}", e);
                    } catch (IllegalAccessException e) {
                        log.error("IllegalAccessException {}", e);
                    } catch (InvocationTargetException e) {
                        log.error("InvocationTargetException {}", e);
                    } finally {
                        // 清理資源
                    }

                }
            }

            workbook.write(out);
        } catch (Exception e) {
            log.error("Exception {}", e);
        }
    }

    /**
     * 讀取excel的數據,返回二維數組,未進行單元格合併處理
     *
     * @param excel
     * @return
     * @throws IOException
     * @throws InvalidFormatException
     */
    public static String[][] readExcel(File excel) throws IOException, InvalidFormatException {

        if (null == excel || !excel.isFile() || !excel.exists()) {
            throw new RuntimeException("excel文件不存在");
        }
        String ext = FilenameUtils.getExtension(excel.getName());
        Workbook wb;
        // 根據文件後綴(xls/xlsx)進行判斷
        if ("xls".equals(ext)) {
            FileInputStream fis = new FileInputStream(excel);
            wb = new HSSFWorkbook(fis);
        } else if ("xlsx".equals(ext)) {
            wb = new XSSFWorkbook(excel);
        } else {
            throw new RuntimeException("excel文件類型錯誤");
        }

        //開始解析
        Sheet sheet = wb.getSheetAt(0);     // 讀取sheet 0
        int firstRowIndex = sheet.getFirstRowNum() + 1;   // 第一行是列名,所以不讀
        int lastRowIndex = sheet.getLastRowNum();
        log.info("讀取 {} 從第 {} 行到第 {} 行", excel.getName(), firstRowIndex + 1, lastRowIndex + 1);

        Row firstRow = sheet.getRow(0);
        int width = firstRow.getLastCellNum();
        for (Row row : sheet) {
            if (width < row.getLastCellNum()) {
                width = row.getLastCellNum();
            }
        }
        String[][] datas = new String[lastRowIndex][];

        boolean containsFormula = false;

        for (int rIndex = firstRowIndex; rIndex <= lastRowIndex; rIndex++) {   //遍歷行
            Row row = sheet.getRow(rIndex);
            if (!isAllRowEmpty(row)) {
                int firstCellIndex = row.getFirstCellNum();
                // 這裏應該以第一列的寬度爲寬度
                int lastCellIndex = width;
                datas[rIndex - 1] = new String[lastCellIndex];
                for (int cIndex = firstCellIndex; cIndex < lastCellIndex; cIndex++) {   //遍歷列
                    Cell cell = row.getCell(cIndex);
                    String key = "";
                    NumberFormat numberFormat = NumberFormat.getNumberInstance();
                    numberFormat.setMaximumFractionDigits(0);
                    if (null != cell) {
                        switch (cell.getCellType()) {
                            // todo 這裏的格式需要根據給定的調整,可以作爲參數傳遞
                            case NUMERIC:
                                if (HSSFDateUtil.isCellDateFormatted(cell)) {
                                    Date date = cell.getDateCellValue();
                                    key = DateFormatUtils.format(date, "yyyy-MM-dd");
                                    break;
                                }
//                                // 2015/8/21 這種類型的日期
//                                if (Pattern.matches("\\d{5}\\.0", cell.toString())) {
//                                    Date date = cell.getDateCellValue();
//                                    key = DateFormatUtils.format(date, "yyyy-MM-dd");
//                                    break;
//                                }

                                double d = cell.getNumericCellValue();
                                String s = numberFormat.format(d);
                                if (s.indexOf(",") >= 0) {
                                    // 這種方法對於自動加".0"的數字可直接解決
                                    // 但如果是科學計數法的數字就轉換成了帶逗號的
                                    // 例如:12345678912345的科學計數法是1.23457E+13
                                    // 經過這個格式化後就變成了字符串“12,345,678,912,345”
                                    // 這也並不是想要的結果,所以要將逗號去掉
                                    s = s.replace(",", "");
                                }
                                key = s;
                                break;
                            case FORMULA: // 對於計算的日期列,無法和數字區分,只能用複製,粘貼爲數值來讀取
                                containsFormula = true;

//                                if (org.apache.poi.ss.usermodel.DateUtil.isCellDateFormatted(cell)) {
//                                    Date temp = cell.getDateCellValue();
//                                    key = new SimpleDateFormat("yyyy-MM-dd").format(temp);
//                                } else {
//                                    key = numberFormat.format(cell.getNumericCellValue());
//                                }
                                key = ((XSSFCell) cell).getRawValue();
                                break;
                            default:
                                key = cell.getStringCellValue().trim();
                        }
                    }
                    datas[rIndex - 1][cIndex] = key;
                }
            }
        }
        if (containsFormula) {
            log.warn("excel包含計算列,返回數據可能存在差異");
        }
        return datas;
    }


    /**
     * 判斷整行是否爲空
     *
     * @param row
     * @return
     */
    private static boolean isAllRowEmpty(Row row) {
        if (Objects.isNull(row)) {
            return true;
        }
        // 總共多少列
        int count = 0;
        // 判斷多少個單元格爲空
        for (int index = 0; index < row.getLastCellNum(); index++) {
            Cell cell = row.getCell(index);
            if (cell == null || cell.getCellType() == CellType.BLANK || StringUtils.isEmpty
                    ((cell + "").trim())) {
                count++;
            }
        }
        if (count == row.getLastCellNum()) {
            return true;
        }
        return false;
    }

}




參考文獻

Java之——導出Excel通用工具類

POI導出excel列寬自適應

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