ExcelUtil.java 11.1 KB
package com.skua.modules.util;

import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.multipart.MultipartFile;

import com.skua.core.util.ConvertUtils;

import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.*;

public class ExcelUtil {
    public static final String W2003 = "2003";

    public static final String W2007 = "2007";

    public static final String XLS = "xls";

    public static final String XLSX = "xlsx";

    private static SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    // 总行数
    public static int totalRows = 0;
    // 总条数
    public static int totalCells = 0;
    // 错误信息接收器
    public static String errorMsg;

    // 获取总行数
    public int getTotalRows() {
        return totalRows;
    }

    // 获取总列数
    public int getTotalCells() {
        return totalCells;
    }

    // 获取错误信息
    public String getErrorInfo() {
        return errorMsg;
    }

    /**
     * 导出简单Excel
     *
     * @param titleList title list
     * @param dataList  data list
     * @return Workbook
     */
    public static HSSFWorkbook exportExcelByMap(List<String> titleList, List<Map<String, Object>> dataList) {
        int rowIndex = 0;
        HSSFWorkbook workbook = new HSSFWorkbook();
        HSSFSheet sheet = workbook.createSheet();
        HSSFFont font = workbook.createFont();
        //设置字体大小
        font.setFontHeightInPoints((short) 12);
        //字体
        font.setFontName("微软雅黑");
        CellStyle style = workbook.createCellStyle();
        style.setBorderTop(CellStyle.BORDER_THIN);
        style.setTopBorderColor(IndexedColors.BLACK.getIndex());
        style.setBorderBottom(CellStyle.BORDER_THIN);
        style.setBottomBorderColor(IndexedColors.BLACK.getIndex());
        style.setBorderLeft(CellStyle.BORDER_THIN);
        style.setLeftBorderColor(IndexedColors.BLACK.getIndex());
        style.setBorderRight(CellStyle.BORDER_THIN);
        style.setRightBorderColor(IndexedColors.BLACK.getIndex());
        style.setBorderTop(CellStyle.BORDER_THIN);
        //水平居中
        style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        //垂直居中
        style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
        style.setFont(font);
        if (titleList != null && !titleList.isEmpty()) {
            int cellIndex = 0;
            HSSFRow row = sheet.createRow(rowIndex++);
            row.setHeightInPoints(30);
            for (int i = 0; i < titleList.size(); i++) {
                String title = titleList.get(i);

                sheet.autoSizeColumn(i);
                sheet.setColumnWidth(i,1000*title.length());

                Cell cell = row.createCell(cellIndex++);
                cell.setCellValue(title == null ? "" : title);
                cell.setCellStyle(style);
            }
            
            if (dataList != null && !dataList.isEmpty()) {
                for (Map<String,Object> map : dataList) {
                	row = sheet.createRow(rowIndex++);
                	for(int i=0;i<titleList.size();i++) {
                		String key = titleList.get(i);
                		if("时间".equals(key)) {
                			key = "time";
                		}if("厂站名称".equals(key)) {
                			key = "departName";
                		}
                		String value = ConvertUtils.getString(map.get(key));
                		 Cell cell = row.createCell(i);
                		 cell.setCellValue(value);
                		 cell.setCellStyle(style);
                	}
                }
            }
        }
        return workbook;
    }

    /**
     * 导出简单Excel
     *
     * @param titleList title list
     * @param dataList  data list
     * @return Workbook
     */
    public static HSSFWorkbook exportSimpleExcelByObject(List<String> titleList, List<List<Map<String,Object>>> dataList) {
        Row row;
        int rowIndex = 0;
        HSSFWorkbook workbook = new HSSFWorkbook();
        Sheet sheet = workbook.createSheet();

        if (titleList != null && !titleList.isEmpty()) {
            int cellIndex = 0;
            row = sheet.createRow(rowIndex++);
            for (String title : titleList) {
                row.createCell(cellIndex++).setCellValue(title == null ? "" : title);
            }
        }

        if (dataList != null && !dataList.isEmpty()) {
            for (List<Map<String,Object>> objList : dataList) {
                if (objList == null || objList.isEmpty()) {
                    continue;
                }
                int cellIndex = 0;
                row = sheet.createRow(rowIndex++);
                for (Object value : objList) {
                    row.createCell(cellIndex++).setCellValue(value == null ? "" : value.toString());
                }
            }
        }

        return workbook;
    }

    /**
     * 填充模板sheet数据
     *
     * @param sheet    Sheet
     * @param dataList data list
     * @param rowIndex 从第几行开始 最小值0
     */
    public static void fillTemplateSheetByMap(Sheet sheet, List<Map<String, Object>> dataList, int rowIndex) {
        if (dataList == null || dataList.isEmpty() || rowIndex < 0) {
            return;
        }
        for (Map<String, Object> map : dataList) {
            if (map == null || map.isEmpty()) {
                continue;
            }
            int cellIndex = 0;
            Row row = sheet.getRow(rowIndex);
            if (row == null) {
                row = sheet.createRow(rowIndex);
            }
            Iterator iterator = map.values().iterator();
            while (iterator.hasNext()) {
                Object value = iterator.next();
                Cell cell = row.getCell(cellIndex);
                if (cell == null) {
                    cell = row.createCell(cellIndex);
                }
                cell.setCellValue(value == null ? "" : value.toString());
                cellIndex++;
            }
            rowIndex++;
        }
    }

    /**
     * 填充模板sheet数据
     *
     * @param sheet    Sheet
     * @param dataList data list
     * @param rowIndex 从第几行开始 最小值0
     */
    public static void fillTemplateSheetByObject(Sheet sheet, List<List<Object>> dataList, int rowIndex) {
        if (dataList == null || dataList.isEmpty() || rowIndex < 0) {
            return;
        }
        for (List<Object> objList : dataList) {
            if (objList == null || objList.isEmpty()) {
                continue;
            }
            int cellIndex = 0;
            Row row = sheet.getRow(rowIndex);
            if (row == null) {
                row = sheet.createRow(rowIndex);
            }
            for (Object value : objList) {
                Cell cell = row.getCell(cellIndex);
                if (cell == null) {
                    cell = row.createCell(cellIndex);
                }
                cell.setCellValue(value == null ? "" : value.toString());
                cellIndex++;
            }
            rowIndex++;
        }
    }

    /**
     * 读EXCEL文件,获取信息集合
     * @param mFile
     * @return
     */
    public static List<Map<String, Object>> getExcelInfo(MultipartFile mFile) {
        String fileName = mFile.getOriginalFilename();// 获取文件名
        try {
            if (!validateExcel(fileName)) {// 验证文件名是否合格
                return null;
            }
            boolean isExcel2003 = true;// 根据文件名判断文件是2003版本还是2007版本
            if (isExcel2007(fileName)) {
                isExcel2003 = false;
            }
            return createExcel(mFile.getInputStream(), isExcel2003);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    /**
     * 根据excel里面的内容读取客户信息
     * @param is      输入流
     * @param isExcel2003   excel是2003还是2007版本
     * @return
     * @throws IOException
     */
    public static List<Map<String, Object>> createExcel(InputStream is, boolean isExcel2003) {
        try {
            Workbook wb = null;
            if (isExcel2003) {// 当excel是2003时,创建excel2003
                wb = new HSSFWorkbook(is);
            } else {// 当excel是2007时,创建excel2007
                wb = new XSSFWorkbook(is);
            }
            return readExcelValue(wb);// 读取Excel里面客户的信息
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }


    /**
     * 读取Excel里的信息
     * @param wb
     * @return
     */
    private static List<Map<String, Object>> readExcelValue(Workbook wb) {
        // 得到第一个shell
        Sheet sheet = wb.getSheetAt(0);
        // 得到Excel的行数
        totalRows = sheet.getPhysicalNumberOfRows();
        // 得到Excel的列数(前提是有行数)
        if (totalRows > 1 && sheet.getRow(0) != null) {
            totalCells = sheet.getRow(0).getPhysicalNumberOfCells();
        }
        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
        Row rowKey = sheet.getRow(0);
        // 循环Excel行数
        for (int r = 1; r < totalRows; r++) {
            Row row = sheet.getRow(r);
            if (row == null) {
                continue;
            }
            // 循环Excel的列
            Map<String, Object> map = new HashMap<String, Object>();
            for (int c = 0; c < totalCells; c++) {
                Cell cellKey = rowKey.getCell(c);
                Cell cell = row.getCell(c);
                if (null != cell) {
                    if (cell.getCellType() == HSSFCell.CELL_TYPE_NUMERIC) {
                        if(!cellKey.getStringCellValue().equals("时间")){
                            map.put(cellKey.getStringCellValue(), cell.getNumericCellValue());
                        }else{
                            Date time = cell.getDateCellValue();
                            String dateTime = formatter.format(time);
                            map.put(cellKey.getStringCellValue(), dateTime);
                        }
                    } else {
                        map.put(cellKey.getStringCellValue(), cell.getStringCellValue());
                    }
                }
            }
            // 添加到list
            list.add(map);
        }
        return list;
    }


    /**
     * 验证EXCEL文件
     * @param filePath
     * @return
     */
    public static boolean validateExcel(String filePath) {
        if (filePath == null || !(isExcel2003(filePath) || isExcel2007(filePath))) {
            errorMsg = "文件名不是excel格式";
            return false;
        }
        return true;
    }

    // @描述:是否是2003的excel,返回true是2003
    public static boolean isExcel2003(String filePath) {
        return filePath.matches("^.+\\.(?i)(xls)$");
    }


    // @描述:是否是2007的excel,返回true是2007
    public static boolean isExcel2007(String filePath) {
        return filePath.matches("^.+\\.(?i)(xlsx)$");
    }
}