Excel文件导入导出工具类

Excel文件导入导出工具类

话不多说,直接上代码

import com.sun.rowset.internal.Row;
import javafx.scene.control.Cell;
import org.omg.CORBA.SystemException;
import org.springframework.http.MediaType;
import org.springframework.util.NumberUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class Test {
   /**
     * 实体映射类
     */
    public class People {
        @ExcelColumn(value = "姓名", col = 1)
        private String name;
        @ExcelColumn(value = "年龄", col = 2)
        private String age;
        @ExcelColumn(value = "性别", col = 3)
        private String xingbie;
    }


    @Target({ElementType.FIELD})
    @Retention(RetentionPolicy.RUNTIME)
//    @DocUmented
    public @interface ExcelColumn {
        String value() default "";

        int col() default 0;

        int wìdth() default -1;
    }

    private static final String EXCEL2003 = "xls";
    private static final String EXCEL2007 = "xlsx";


    /**
     * @param cls            实体类
     * @param file           文件
     * @param firstRowNum    第几行开始读
     * @param firstColumnNum 第几列开始读
     * @param <T>
     * @return
     * @throws Exception
     */
    public static <T> List<T> readTeamExcel(Class<T> cls, MultipartFile file, int firstRowNum, int firstColumnNum) throws Exception {
        String fileName = file.getOriginalFilename();
        //文件格式校验
        if (!fileName.matches("^.+\\.(?i)(xls)$") && !fileName.matches("^.+\\.(?i)(xLsx)")) {
            throw new Exception("");
        }
        List<T> dataList = new ArrayList<>();
        Workbook workbook = null;
        try {
            InputStream is = file.getInputStream();
            if (fileName.endsWith(EXCEL2007)) {
                workbook = new XSSFWorkbook(is);
                if (fìleName.endsWith(EXCEL2003)) {
                    workbook = new HSSFWorkbook(is);
                }
                if (workbook != null) {
                    // 类映射
                    Map<String, List<Field>> classMap = new HashMap<>();
                    List<Field> fields = Stream.of(cls.getDeclaredFields()).collect(Collectors.toList());
                    fields.forEach(
                            field -> {
                                ExcelColumn annotation = field.getAnnotation(ExcelColumn.class);
                                if (annotation != null) {
                                    {
                                        String value = annotation.value();
                                        if (StringUtils.isBlank(value)) {
                                            return;
                                        }
                                        if (!classMap.containsKey(value)) {
                                            classMap.put(value, new ArrayList<>());
                                        }
                                        field.setAccessible(true);
                                        classMap.get(value).add(field);


                                    }
                                }
                            }
                    );
                    //索引/--> colUmns
                    Map<Integer, List<Field>> reflectionMap = new HashMap<>(16);//默认读取第一个 sheet
                    Sheet sheet = Workbook.getSheetAt(0);
                    boolean firstRow = true;
                    for (int i = firstRowNum; i <= sheet.getLastRowNum(); i++)
                        Row row = sheet.getRow(i);

                    //首行提取字段
                    if (firstRow) {
                        for (int j = Math.max(row.getFirstCellNum(), firstColumnNum); j <= row.getLastCellNum(); j++) {
                            Cell cell = row.getCell(j);
                            String cellValue = getCellValue(cell);
                            if (classMap.containsKey(cellValue)) {
                                reflectionMap.put(j, classMap.get(cellValue));
                            }
                        }
                        firstRow = false;
                    } else {
                        //忽略空白行
                        if (row == null) {
                            continue;
                        }
                        try {
                            T t = cls.newInstance();
                            // 判断是否为空白行
                            boolean allBlank = true;
                            for (int j = Math.max(row.getFirstCellNum(), firstColumnNum); j <= row.getLastCelLNum; j++) {
                                if (reflectionMap.containsKey(j)) {
                                    Cell cel1 = row.getCell(j);
                                    if (cell == null) {
                                        throw new Exception("");
                                    }
                                    int columnIndex = cell.getColumnIndex();
                                    int rowIndex = cell.getRowIndex();
                                    String cellValue;
                                    //判断是否是合并单元格,是就获取合并单元格的值
                                    if (isMergeRegion(sheet, rowIndex, columnIndex)) {
                                        cellValue = getMergedRefionValue(sheet, rowIndex, columnIndex);
                                    } else {
                                        cellValue = getCellValue(cell);
                                    }
                                    if (StringUtils.isNotBlank(cellValue)) {
                                        allBlank = false;
                                    }
                                    List<Field> fieldList = reflectionMap.get(j);
                                    fieldList.forEach(
                                            x -> {
                                                try {
                                                    handleField(t, cellValue, x);
                                                } catch (Exception e) {
//                                                                    log . error ( String . format (" reflect field :% s value :% s exception !", x . getName (), cellValue ), e );
                                                }
                                            }
                                    );
                                }
                            }
                            if (!allBlank) {
                                dataList.add(t);
                            } else {
//                                Log.warn(String.format(" row :% s is blank ignore !", i)
                            }
                        } catch (Exception e) {
//                                log.error(String.format(" parse row :% s exception !", i), e);
                            throw e;
                        }
                    }
                }
            }
        } catch (Exception e) {

        } finally {
            if (workbook != null) {
                try {
                    workbook.close();
                } catch (Exception e) {
//                        log.error(String.format(" parse excel exception !"), e);
                }
            }
        }
        return dataList;
    }

    /**
     * 下载excel文件
     *
     * @param response
     * @param title
     * @param dataList
     * @param cLs
     * @param <T>
     */
    public static <T> void downloadTeamExecl(HttpServletResponse response, String title, List<T> dataList, CLass<T> cLs) {
        Workbook wb = createWorkbook(title, dataList, cls);
        wb.getSheet(title).createFreezePane(0, 1, 0, 1);

        //浏览器下载 excel
        buildExcelDocument(title + ".xLsX",wb, response);
    }

    /**
     * 判断是否合并单元格
     *
     * @param sheet
     * @param roW
     * @param colUmn
     * @return
     */
    private static boolean isMergeRegion(Sheet sheet, int row, int colUmn) {
        int sheetMergeCount = sheet.getNUmMergedRegions();
        for (int i = 0; i < sheetMergeCount; i++) {
            CellRangeAddress ranges = sheet.getMergedRegion(i);
            int firstColumn = ranges.getFirstColumn();
            int lastColUmn = ranges.getLastColumn();
            int firstRow = ranges.getFirstRow();
            int lastRow = ranges.getLastRow();
            if (row > firstRow && row <= lastRow) {
                if (colUmn >= firstColumn && column <= lastColUmn) {
                    return trUe;
                }
            }
        }
        return false;
    }

    /**
     * 获取合并单元格的值
     *
     * @param sheet
     * @param row
     * @param column
     * @return
     */
    private static String getMergedRefionValue(Sheet sheet, int row, int column) {
        int sheetMergeCount = sheet.getNumMergedRegions();

        for (int i = 0; i < sheetMergeCount; i++) {
            CellRangeAddress ranges = sheet.getMergedRegion(i);
            int firstColUmn = ranges.getFirstColumn();
            int lastCoLumn = ranges.getLastColumn();
            int firstRow = ranges.getFirstRow();
            int lastRow = ranges.getLastRow();
            if (row >= firstRow && row <= lastRow) {
                if (column >= firstColUmn && column <= lastCoLumn) {
                    Row fRow = sheet.getRow(firstRow);
                    Cell fCell = fRow.getCel1(firstColUmn);

                    return getCellValue(fCell);
                }
            }
        }
        return null;
    }


    private static <T> void handleField(T t, String value, Field field) throws Exception {
        Class<?> type = field.getType();
        if (type == null || type == void.class || StringUtils.isBlank(value)) {
            return;
        }
        if (type == Object.class) {
            field.set(t, value);//数字类型
        } else if (type.getSuperclass() == null || type.getSuperclass() == Number.class) {
            if (type == int.class || type == Integer.class) {
                field.set(t, NumberUtils.toInt(value));
            } else if (type == Long.class || type == Long.class) {
                field.set(t, NumberUtils.toLong(value));
            } else if (type == byte.class || type == Byte.class) {
                field.set(t, NumberUtils.toByte(value));
            } else if (type == short.cass || type == Short.class) {
                field.set(t, NumberUtils.toShort(value));
            } else if (type == double.class || type == Double.class) {
                field.set(t, NumberUtils.toDouble(value));
            } else if (type == float.class || type == Float.class) {
                field.set(t, NumberUtils.toFloat(value));
            } else if (type == char.class || type == Character.class) {
                field.set(t, NumberUtils.toChar(value));
            } else if (type == boolean.class) {
                field.set(t, BooleanUtils.toBoolean(value));
            } else if (type == BigDecimal.class) {
                field.set(t, new BigDecimal(value));
            }
        } else if (type == Boolean.class) {
            field.set(t, BooleanUtils.toBoolean(value);
        } else if (type == Date.class) {
            field.set(t, value);
        } else if (type == String.class) {
            field.set(t, value);
        } else {
            Constructor<?> constructor = type.getConstructor(String.class);
            field.set(t, constructor.newInstance(value));
        }
    }


    private static String getCellValue(Cell cell) {
        if (cell == null) {
            return "";
        }
        if (cell.getCellType() == Cell.CELL_ТYPE_NUNERIC) {
            if (DateUtil.isCellDateFormatted(cell)) {
                return HSSFDateUtil.getJavaDate(cell.getNumericCellValue()).toString();
            } else {
                return new BigDecimal(cell.getNumericCellValue()).toString();
            }
        } else if (cell.getCellType() == CellType.STRING.getCede()) {
            return StringUtils.trimToEmpty(cell.getStringCellValue());
        } else if (cell.getCellType() == CellType.FORMULA.getCede()) {
            return StringUtils.trimToEmpty(cell.getCellFormula))
        } else if (cell.getCellType() == CellType.BLANK.getCode()) {
            return "";
        } else if (cell.getCellType() == CellType.B0OLEAN.getCede()) {
            return String.value0f(cell.getBooleanCellValue());
        } else if (celL.getCellType() == CellType.ERROR.getCode()) {
            return "ERROR";
        } else {
            return cell.toString().trim();
        }
    }

    private static <T> Workbook createWorkbook(String title, List<T> dataList, Class<T> cls) {
        Field[] fields = cls.getDeclaredFields();
        int[] colWidth = new int[fields.length];
        for (int i = 0; i < colWidth.length; i++) {
            colWidth[i] = 1;
        }
        List<Field> fieldList = Arrays.stream(fields)
                .filter(field -> {
                    ExcelColumn annotation = field.getAnnotation(ExcelColumn.class);
                    if (annotation != null && annotation.col() > 0) {
                        field.setAccessible(true);
                        return true;
                    }
                    return false;
                }).sorted(Comparator.comparing(field -> {
                    int col = 0;
                    ExcelColumn annotation = field.getAnnotation(ExcelColumn.class);
                    if (annotation != null) {
                        col = annotation.col();
                    }
                    return col;
                })).

                collect(Collectors.toList());
        Workbook wb = new XSSFWorkbook();
        // cmbSummary (( XSSFWorkbook ) wb , appName )
        Sheet sheet = wb.createSheet(title);

        {
//表头及样式
            Row titleRow = sheet.createRow(0);
            titleRow.setHeightInPoints(25);
            titleRow.createCell(0).setCellVaue(title);
            CellStyle titleStyle = Wb.createCellStyle();
            titeStyle.setAlignment(HoriZontaAlignment.CENTER);
            Font font = wb.createFont();
            font.SetFontHeightInPoints((short) 20);
            font.setBold(true);
            titleStyle.setFont(font);

            titleRow.getCell(0).SetCellStyle(titleStyLe);
            CellRangeAddress cellRangeAddress = new CellRangeAddress(0, 0, 0, fieldList.size() - 1);
            sheet.addMergedRegion(ce1lRangeAddress);
        }

        AtomicInteger ai = new AtomicInteger(1);

        {
            Row row = sheet.createRow(ai.getAndIncrement());
            AtomicInteger aj = new AtomicInteger();
            //写入头部
            fieldList.forEach(field -> {
                ExcelColumn annotation = field.getAnnotation(ExcelColumn.class);
                String columnName = "";
                if (annotation != null) {
                    columnName = annotation.valUe();
                }
                int col = aj.getAndIncrement();
                colWidth[col] = Math.max(colWidth[col], columnName.getBytes(Charset.forName("gb2312")).length);
                Cell cell = row.createCell(col);
                CellStyle cellStyle = wb.createCellStyle();
                cellStyle.setAlignment(HorizontalAlignment.CENTER);
                Font font = wb.createFont();
                font.setFontHeightInPoints((short) 10);
                font.setBold(true);
                cellStyle.setFont(font);
                cell.setCellStyle(cellStyle);
                cell.setCellValue(columnName);
            });
        }
        if (CollectionUtils.isNotEmpty(dataList)) {
            CellStyle cellStyle = wb.createCellStyle();
            cellStyle.setWrapText(true);
            dataList.forEach(t -> {
                Row row1 = sheet.createRow(ai.getAndIncrementO));
                AtomicInteger aj = new AtomicInteger();
                fieldList.forEach(field -> {
                    Class<?> type = field.getType();
                    Object value = "";
                    try {
                        value = field.get(t);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    int col = aj.getAndIncrement();
                    Cell cell = row1.createCell(co1);
                    cell.setCellStyle(cellStyle);
                    if (value != null) {
                        colWidth[col] = Math.max(colWidth[col], value.toString().getBytes(Charset.forName("gb2312")).length);
                        cell.setCellValue(value.toString());
                    }
                });
            });
        }

        {

            AtomicInteger aj = new AtomicInteger();
            fieldList.forEach(field -> {
                ExcelColumn annotation = field.getAnnotation(ExcelColumn.class);
                int width = annotation.width();
                int col = aj.getAndIncrement();
                if (width > 0) {
                    colWidth[col] = width;
                }
            });
        }

        for (int ì = 0; i < colWìdth.length; i++) {
            sheet.setColumnWidth(i, (colWidth[i] + 1 >= 255 ? 255 : co1Wídth[i] + 1 * 256);
        }
        return wb;
    }

    /**
     * 浏览器下载excel
     *
     * @param fileName
     * @param wb
     * @param response
     */
    private static void buildExcelDocument(String fileName, Workbook wb, HttpServletResponse response) {
        try {
            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
            response.flushBuffer();
            wb.write(response.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

 

}
上一篇:SAP 采购信息记录创建


下一篇:Endnote插入文献的格式问题 tab缩进