POI EXCEL处理

package com.wnsys.admin.util;

import com.iscas.quickframe.domain.p.User;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.streaming.SXSSFSheet;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;

import java.beans.PropertyDescriptor;
import java.io.*;
import java.lang.reflect.Method;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author: zhuquanwen
 * @Description:
 * @Date: 2018/1/3 17:41
 * @Modified:
 **/
public class ExcelUtils {
//    private ExcelUtils(){
//
//    }
//
    public static class ExcelResult<T>{
        private String sheetName; //sheet名称
        private LinkedHashMap<String,String> header; //表头键值对 key : en ; value :ch
        private List<T> content; //Excel数据
        private LinkedHashMap<String,Object> cellStyle; //列的样式
        private Object headerStyle; //表头的样式

        public String getSheetName() {
            return sheetName;
        }

        public void setSheetName(String sheetName) {
            this.sheetName = sheetName;
        }

        public LinkedHashMap<String, String> getHeader() {
            return header;
        }

        public void setHeader(LinkedHashMap<String, String> header) {
            this.header = header;
        }

        public List<T> getContent() {
            return content;
        }

        public void setContent(List<T> content) {
            this.content = content;
        }

        public LinkedHashMap<String, Object> getCellStyle() {
            return cellStyle;
        }

        public void setCellStyle(LinkedHashMap<String, Object> cellStyle) {
            this.cellStyle = cellStyle;
        }

        public Object getHeaderStyle() {
            return headerStyle;
        }

        public void setHeaderStyle(Object headerStyle) {
            this.headerStyle = headerStyle;
        }
}

    public static String NO_DEFINE = "no_define";//未定义的字段
    public static int DEFAULT_COLOUMN_WIDTH = 17;


    /*Excel写入文件*/
    public static <T> void exportXLSExcel(List<ExcelResult<T>> excelResults,int colWidth,
                                       String path) throws Exception{
        File file = new File(path);
        OutputStream out = new FileOutputStream(file);
        exportXLSExcel(excelResults,colWidth,out);
    }

    public static HSSFCellStyle getHSSFCellStyle(HSSFWorkbook workbook){
        // 单元格样式
        HSSFCellStyle cellStyle = workbook.createCellStyle();
        cellStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
        cellStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN);
        cellStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);
        cellStyle.setBorderRight(HSSFCellStyle.BORDER_THIN);
        cellStyle.setBorderTop(HSSFCellStyle.BORDER_THIN);
        cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        cellStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
        HSSFFont cellFont = workbook.createFont();
        cellFont.setBoldweight(HSSFFont.BOLDWEIGHT_NORMAL);
        cellStyle.setFont(cellFont);
        return cellStyle;
    }

    public static CellStyle getSXSSFCellStyle(SXSSFWorkbook workbook){
        // 单元格样式
        CellStyle cellStyle = workbook.createCellStyle();
        cellStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
        cellStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN);
        cellStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);
        cellStyle.setBorderRight(HSSFCellStyle.BORDER_THIN);
        cellStyle.setBorderTop(HSSFCellStyle.BORDER_THIN);
        cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        cellStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
        Font cellFont = workbook.createFont();
        cellFont.setBoldweight(HSSFFont.BOLDWEIGHT_NORMAL);
        cellStyle.setFont(cellFont);
        return cellStyle;
    }

    //样式
    public static HSSFCellStyle getHSSFHeaderStyle(HSSFWorkbook workbook){
        // 列头样式
        HSSFCellStyle headerStyle = workbook.createCellStyle();
        headerStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
        headerStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN);
        headerStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);
        headerStyle.setBorderRight(HSSFCellStyle.BORDER_THIN);
        headerStyle.setBorderTop(HSSFCellStyle.BORDER_THIN);
        headerStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        HSSFFont headerFont = workbook.createFont();
        headerFont.setFontHeightInPoints((short) 12);
        headerFont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
        headerStyle.setFont(headerFont);
        return headerStyle;
    }

    //样式
    public static CellStyle getSXSSFHeaderStyle(SXSSFWorkbook workbook){
        // 列头样式
        CellStyle headerStyle = workbook.createCellStyle();
        headerStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
        headerStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN);
        headerStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);
        headerStyle.setBorderRight(HSSFCellStyle.BORDER_THIN);
        headerStyle.setBorderTop(HSSFCellStyle.BORDER_THIN);
        headerStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        Font headerFont = workbook.createFont();
        headerFont.setFontHeightInPoints((short) 12);
        headerFont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
        headerStyle.setFont(headerFont);
        return headerStyle;
    }


    /*Excel写入文件*/
    public static <T> void exportXLSXExcel(List<ExcelResult<Map>> excelResults , int colWidth,
                                           String path) throws Exception{
        File file = new File(path);
        OutputStream out = new FileOutputStream(file);
        exportXLSXExcel(excelResults,colWidth,out);
    }

    /*Excel写入流*/
    public static <T> void exportXLSXExcel(List<ExcelResult<T>> excelResults ,int colWidth,
                                          OutputStream out) throws Exception{
        // 声明一个工作薄
        SXSSFWorkbook   workbook = new SXSSFWorkbook();


        for (Iterator<ExcelResult<T>> i = excelResults.iterator() ;i.hasNext(); ){
            ExcelResult<T> excelResult = i.next();
            List<T> list = excelResult.getContent();
            LinkedHashMap<String,String> headerMap = excelResult.getHeader();
            LinkedHashMap<String,?> styleMap = excelResult.getCellStyle();
            CellStyle headerStyle = (CellStyle) excelResult.getHeaderStyle();
            Sheet sheet = workbook.createSheet(excelResult.getSheetName());

            int minBytes = colWidth<DEFAULT_COLOUMN_WIDTH?DEFAULT_COLOUMN_WIDTH:colWidth;//至少字节数
            int[] arrColWidth = new int[headerMap.size()];
            // 产生表格标题行,以及设置列宽
            String[] properties = new String[headerMap.size()];
            String[] headers = new String[headerMap.size()];
            int ii = 0;
            for (Iterator<String> iter = headerMap.keySet().iterator(); iter.hasNext();) {
                String fieldName = iter.next();
                properties[ii] = fieldName;
                headers[ii] = fieldName;
                int bytes = fieldName.getBytes().length;
                arrColWidth[ii] =  bytes < minBytes ? minBytes : bytes;
                sheet.setColumnWidth(ii,arrColWidth[ii]*256);
                ii++;
            }
            Row headerRow = sheet.createRow(0); //列头 rowIndex =1
            for(int j=0;j<headers.length;j++)
            {
                headerRow.createCell(j).setCellValue(headerMap.get(headers[j]));
                if(headerStyle != null){
                    headerRow.getCell(j).setCellStyle(headerStyle);
                }else{
                    CellStyle cellStyle = workbook.createCellStyle();
                    DataFormat format = workbook.createDataFormat();
                    cellStyle.setDataFormat(format.getFormat("@"));
                    headerRow.getCell(j).setCellStyle(cellStyle);
                    headerRow.getCell(j).setCellType(Cell.CELL_TYPE_STRING);
                }
            }
            if(!CollectionUtils.isEmpty(list)){
                for(int m=0; m< list.size(); m++){
                    Row dataRow = sheet.createRow(m + 1);
                    T t = list.get(m);
                    for(int j=0;j<headers.length;j++) {
                        Cell newCell = dataRow.createCell(j);
                        Object cellValue = "";
                        if(t instanceof Map){
                            cellValue = ((Map) t).get(headers[j]);
                        }else{
                            //如果是Java对象,利用反射
                            PropertyDescriptor pd = new PropertyDescriptor(headers[j], t.getClass());
                            Method getMethod = pd.getReadMethod();//获得get方法
                            cellValue = getMethod.invoke(t);//执行get方法返回一个Object
                        }
                        newCell.setCellValue(cellValue == null ? "" : String.valueOf(cellValue));
                        if(styleMap != null && styleMap.get(headers[j]) != null){
                            newCell.setCellStyle((CellStyle) styleMap.get(headers[j]));
                        }else{
                            CellStyle cellStyle = workbook.createCellStyle();
                            DataFormat format = workbook.createDataFormat();
                            cellStyle.setDataFormat(format.getFormat("@"));
                            newCell.setCellStyle(cellStyle);
                            newCell.setCellType(Cell.CELL_TYPE_STRING);
                        }
                    }
                }
            }
        }
        // 自动调整宽度
        /*for (int i = 0; i < headers.length; i++) {
            sheet.autoSizeColumn(i);
        }*/
        workbook.write(out);
        out.flush();
    }

    /*Excel写入流*/
    public static <T> void exportXLSExcel(List<ExcelResult<T>> results ,int colWidth,
                                       OutputStream out) throws Exception{
        // 声明一个工作薄
        HSSFWorkbook workbook = new HSSFWorkbook();
        for (Iterator<ExcelResult<T>> i = results.iterator() ;i.hasNext(); ){
            ExcelResult<T> excelResult = i.next();
            List<T> list = excelResult.getContent();
            if(!CollectionUtils.isEmpty(list) && list.size() > 65534){
                throw new Exception("Excel超过了允许的大小");
            }
            LinkedHashMap<String,String> headerMap = excelResult.getHeader();
            LinkedHashMap<String,?> styleMap = excelResult.getCellStyle();
            HSSFCellStyle headerStyle = (HSSFCellStyle) excelResult.getHeaderStyle();
            HSSFSheet sheet = workbook.createSheet(excelResult.getSheetName());
            int minBytes = colWidth<DEFAULT_COLOUMN_WIDTH?DEFAULT_COLOUMN_WIDTH:colWidth;//至少字节数
            int[] arrColWidth = new int[headerMap.size()];
            // 产生表格标题行,以及设置列宽
            String[] properties = new String[headerMap.size()];
            String[] headers = new String[headerMap.size()];
            int ii = 0;
            for (Iterator<String> iter = headerMap.keySet().iterator(); iter.hasNext();) {
                String fieldName = iter.next();
                properties[ii] = fieldName;
                headers[ii] = fieldName;
                int bytes = fieldName.getBytes().length;
                arrColWidth[ii] =  bytes < minBytes ? minBytes : bytes;
                sheet.setColumnWidth(ii,arrColWidth[ii]*256);
                ii++;
            }
            HSSFRow headerRow = sheet.createRow(0); //列头 rowIndex =1
            for(int j=0;j<headers.length;j++)
            {
                headerRow.createCell(j).setCellValue(headerMap.get(headers[j]));
                if(headerStyle != null){
                    headerRow.getCell(j).setCellStyle(headerStyle);
                }else{
                    HSSFCellStyle cellStyle = workbook.createCellStyle();
                    DataFormat format = workbook.createDataFormat();
                    cellStyle.setDataFormat(format.getFormat("@"));
                    headerRow.getCell(j).setCellStyle(cellStyle);
                    headerRow.getCell(j).setCellType(HSSFCell.CELL_TYPE_STRING);
                }
            }
            if(!CollectionUtils.isEmpty(list)){
                for(int m=0; m< list.size(); m++){
                    HSSFRow dataRow = sheet.createRow(m + 1);
                    T t = list.get(m);
                    for(int j=0;j<headers.length;j++) {
                        HSSFCell newCell = dataRow.createCell(j);
                        Object cellValue = "";
                        if(t instanceof Map){
                            cellValue = ((Map) t).get(headers[j]);
                        }else{
                            //如果是Java对象,利用反射
                            PropertyDescriptor pd = new PropertyDescriptor(headers[j], t.getClass());
                            Method getMethod = pd.getReadMethod();//获得get方法
                            cellValue = getMethod.invoke(t);//执行get方法返回一个Object
                        }

                        newCell.setCellValue(cellValue == null ? "" : String.valueOf(cellValue));
                        if(styleMap != null && styleMap.get(headers[j])!= null){
                            newCell.setCellStyle((HSSFCellStyle) styleMap.get(headers[j]));
                        }else{
                            HSSFCellStyle cellStyle = workbook.createCellStyle();
                            HSSFDataFormat format = workbook.createDataFormat();
                            cellStyle.setDataFormat(format.getFormat("@"));
                            newCell.setCellStyle(cellStyle);
                            newCell.setCellType(HSSFCell.CELL_TYPE_STRING);
                        }
                    }
                }
            }
        }
        // 自动调整宽度
        /*for (int i = 0; i < headers.length; i++) {
            sheet.autoSizeColumn(i);
        }*/
            workbook.write(out);
            out.flush();
    }



    public void createXLSTemplet(List list ){

    }

    private static void readXLSXToListMap(MultipartFile multipartFile,Map<String, List> resultMap) throws IOException, InvalidFormatException {

        // IO流读取文件
        XSSFWorkbook wb = null;
        try(
                InputStream input = multipartFile.getInputStream();
        )
        {
            wb = (XSSFWorkbook) WorkbookFactory.create(input);
            //读取sheet(页)
            for(int numSheet=0;numSheet<wb.getNumberOfSheets();numSheet++){
                List<Map> list = new ArrayList<Map>();
                XSSFSheet xssfSheet = wb.getSheetAt(numSheet);
                if(xssfSheet == null){
                    continue;
                }
                int totalRows = xssfSheet.getLastRowNum();
                //读取Row,从第二行开始
                for(int rowNum = 1;rowNum <= totalRows;rowNum++){
                    XSSFRow xssfRow = xssfSheet.getRow(rowNum);
                    if(xssfRow!=null){
                        Map map = new HashMap();
                        int totalCells = xssfRow.getLastCellNum();
                        //读取列,从第一列开始
                        for(int c=0;c< totalCells;c++){
                            XSSFCell cell = xssfRow.getCell(c);
                            if(cell == null){
                                continue;
                            }
                            Object value = null;
                            switch (cell.getCellType()) {
                                case XSSFCell.CELL_TYPE_NUMERIC:
                                    value = cell.getNumericCellValue();

                                    break;
                                case XSSFCell.CELL_TYPE_STRING: // 字符串
                                    value = cell.getStringCellValue();
                                    break;
                                case XSSFCell.CELL_TYPE_BOOLEAN: // Boolean
                                    value = cell.getBooleanCellValue();
                                    break;
                                case XSSFCell.CELL_TYPE_FORMULA: // 公式
                                    value = cell.getCellFormula() + "";
                                    break;
                                case XSSFCell.CELL_TYPE_BLANK: // 空值
                                    value = "";
                                    break;
                                case XSSFCell.CELL_TYPE_ERROR: // 故障
                                    value = "非法字符";
                                    break;
                            }
                            String key = xssfSheet.getRow(0).getCell(c).getStringCellValue();
                            map.put(key,value);
                        }
                        list.add(map);
                    }
                }
                if(resultMap.get(xssfSheet.getSheetName()) != null){
                    List<Map> listx = resultMap.get(xssfSheet.getSheetName());
                    listx.addAll(list);
                }else{
                    resultMap.put(xssfSheet.getSheetName(),list);
                }
            }

        }
    }

    private static void  readXLSToListMap(MultipartFile multipartFile,Map<String, List> resultMap) throws
            IOException, InvalidFormatException {
        // IO流读取文件
        HSSFWorkbook wb = null;
        try (
                InputStream input = multipartFile.getInputStream();
        ) {
            wb = new HSSFWorkbook(input);
            //读取sheet(页)
            for (int numSheet = 0; numSheet < wb.getNumberOfSheets(); numSheet++) {
                List<Map> list = new ArrayList<Map>();
                HSSFSheet xssfSheet = wb.getSheetAt(numSheet);
                if (xssfSheet == null) {
                    continue;
                }
                int totalRows = xssfSheet.getLastRowNum();
                //读取Row,从第二行开始
                for (int rowNum = 1; rowNum <= totalRows; rowNum++) {
                    HSSFRow xssfRow = xssfSheet.getRow(rowNum);
                    if (xssfRow != null) {
                        Map map = new HashMap();
                        int totalCells = xssfRow.getLastCellNum();
                        //读取列,从第一列开始
                        for (int c = 0; c < totalCells; c++) {
                            HSSFCell cell = xssfRow.getCell(c);
                            if(cell == null){
                                continue;
                            }
                            Object value = null;
                            switch (cell.getCellType()) {
                                case HSSFCell.CELL_TYPE_NUMERIC:
                                    value = cell.getNumericCellValue();

                                    break;
                                case HSSFCell.CELL_TYPE_STRING: // 字符串
                                    value = cell.getStringCellValue();
                                    break;
                                case HSSFCell.CELL_TYPE_BOOLEAN: // Boolean
                                    value = cell.getBooleanCellValue();
                                    break;
                                case HSSFCell.CELL_TYPE_FORMULA: // 公式
                                    value = cell.getCellFormula() + "";
                                    break;
                                case HSSFCell.CELL_TYPE_BLANK: // 空值
                                    value = "";
                                    break;
                                case HSSFCell.CELL_TYPE_ERROR: // 故障
                                    value = "非法字符";
                                    break;
                            }
                            String key = xssfSheet.getRow(0).getCell(c).getStringCellValue();
                            map.put(key, value);
                        }
                        list.add(map);
                    }
                }
                if(resultMap.get(xssfSheet.getSheetName()) != null){
                    List<Map> listx = resultMap.get(xssfSheet.getSheetName());
                    listx.addAll(list);
                }else{
                    resultMap.put(xssfSheet.getSheetName(),list);
                }
            }
        }

    }

    /*将EXCEL读取到listmap中*/
    public static void readExcelToListMap(MultipartFile multipartFile, Map<String, List> resultMap)
            throws IOException, InvalidFormatException {
        if(multipartFile.getOriginalFilename().endsWith(".xls")){
            readXLSToListMap(multipartFile, resultMap);
        }else if(multipartFile.getOriginalFilename().endsWith(".xlsx")){
            readXLSXToListMap(multipartFile, resultMap);
        }
    }



}

猜你喜欢

转载自blog.csdn.net/u011943534/article/details/79609001