实体List导出为excel表格(支持excel打开加密解密)

		<dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>3.17</version>
        </dependency>
package cn.hsa.req.common.utils;

import cn.hsa.req.annotation.ExcelField;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.openxml4j.opc.PackageAccess;
import org.apache.poi.poifs.crypt.EncryptionInfo;
import org.apache.poi.poifs.crypt.EncryptionMode;
import org.apache.poi.poifs.crypt.Encryptor;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.*;
import java.lang.reflect.Field;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 *  支持操作xls、xlsx格式表格
 * @param <T>
 */
public class ExcelUtil<T> {

    //日期支持以下以下格式
    private static SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    private static SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");

    private static SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy.MM.dd");

    private static SimpleDateFormat sdf3 = new SimpleDateFormat("yyyy年MM月dd日");

    /**
     * 获取表格列头和实体的对应关系
     * @param aClass
     * @return
     */
    public static<T> JSONObject getJsonField(Class<T> aClass){
        Field[] fields = aClass.getDeclaredFields();
        JSONObject js = new JSONObject();
        for (int i = 0; i < fields.length; i++) {
            ExcelField annotation = fields[i].getAnnotation(ExcelField.class);
            if (annotation!=null){
                if (annotation.ignore()==true){
                    continue;
                }
                else {
                    if (!annotation.value().equals("")){
                        String value = annotation.value();
                        js.put(value,fields[i].getName());

                    }
                    else {
                        js.put(fields[i].getName(),fields[i].getName());
                    }
                }
            }
            else {
                js.put(fields[i].getName(),fields[i].getName());
            }
        }
        return js;
    }


    /**
     * 生成xlsx格式表格文件,可上传的数据量更大
     * @param aClass
     * @param list
     * @param fileName
     * @return File
     * @throws Exception
     */
    public static<T> File createXlsxExcel(Class<T> aClass, List<T> list, String fileName) throws Exception{
        // 创建一个webbook,对应一个Excel文件
//        Workbook wb =  WorkbookFactory.create(new File(fileName));
        Workbook wb = new XSSFWorkbook();
        CellStyle textType = wb.createCellStyle();
        CellStyle dateType = wb.createCellStyle();
        DataFormat dataFormat = wb.createDataFormat();
        textType.setDataFormat(dataFormat.getFormat("@"));
        dateType.setDataFormat(dataFormat.getFormat("yyyy年m月d日"));

        // 在webbook中添加一个sheet,对应Excel文件中的sheet
        Sheet sheet = wb.createSheet("sheet1");
        // 在sheet中添加表头第0行,注意老版本poi对Excel的行数列数有限制short
        Row row = sheet.createRow(0);
        // 添加标题行
        Cell cell = null;
        Field[] fields = aClass.getDeclaredFields();
        List<Field> excelField = new ArrayList<>();
        int excelNo=0;
        for (int i = 0; i < fields.length; i++) {
            ExcelField annotation = fields[i].getAnnotation(ExcelField.class);
            if (annotation!=null){
                if (annotation.ignore()==true){
                    continue;
                }
                else {
                    excelField.add(fields[i]);
                    // 获取行内对应单元格
                    cell = row.createCell(excelNo++);
                    // 单元格赋值
                    String value = annotation.value();
                    if (value.equals("")){
                        cell.setCellValue(fields[i].getName());
                    }
                    else {
                        cell.setCellValue(value);
                    }
                }
            }
            else {
                cell = row.createCell(excelNo++);
                cell.setCellValue(fields[i].getName());
                excelField.add(fields[i]);
            }
        }
        // 写入实体数据,实际应用中这些数据从数据库得到,list中字符串的顺序必须和数组strArray中的顺序一致
        int i = 0;
        for (int j = 0; j < list.size(); j++) {
            T t = list.get(i);
            i++;
            row = sheet.createRow(i );
            // 添加数据行
            //数据转为Json
            String json= JSON.toJSONString(t);//关键
            JSONObject parse = (JSONObject) JSONObject.parse(json);
            for (int z = 0; z < excelField.size(); z++) {
                Field field=excelField.get(z);
                ExcelField annotation = field.getAnnotation(ExcelField.class);
                boolean ignore =false;
                if (annotation!=null){
                    ignore = annotation.ignore();
                }
                if (!ignore){
                    cell = row.createCell(z);
                    cell.setCellStyle(textType);
                    // 获取行内对应单元格
                    String name = field.getName();
                    Object o = parse.get(name);
                    // 单元格赋值
                    if (o instanceof Long){
                        long o1 = (long) o;
                        Date date = null;
                        SimpleDateFormat simpleDateFormat = null;
                        try {
                            date = new Date();
                            date.setTime(o1);
                            simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                            cell.setCellValue(simpleDateFormat.format(date));
                        } catch (Exception e) {
                            e.printStackTrace();
                            cell.setCellValue(o1);
                        }

                    }
                    else if (o instanceof String){
                        cell.setCellValue((String) o);
                    }
                    else if (o instanceof Double){
                        cell.setCellValue((double) o);
                    }
                    else if (o instanceof Boolean){
                        cell.setCellValue((boolean) o);
                    }
                }

            }
        }
        // 第六步,将文件存到指定位置
        FileOutputStream fout = new FileOutputStream(fileName);
        try {
            wb.write(fout);
            fout.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        finally {
            fout.close();
        }

        return new File(fileName);
    }

    /**
     * 读取excel文件
     * @param aClass
     * @param file
     * @param <T>
     * @return
     */
    public static<T> JSONArray readXlsxExcel(Class<T> aClass,File file) throws Exception {
        JSONArray array = new JSONArray();
        Workbook work = new XSSFWorkbook(new FileInputStream(file.getAbsolutePath()));// 得到这个excel表格对象
        Sheet sheet = work.getSheetAt(0);//得到第一个sheet
        int rowNo = sheet.getLastRowNum(); //得到行数
        //获取首行列头
        Row row = sheet.getRow(0);
        short lastCellNum = row.getLastCellNum();
        List<String> fieldNames = new ArrayList<>();
        for (int i = 0; i < lastCellNum; i++) {
            Cell cell = row.getCell(i);
            if (cell!=null){
                String stringCellValue = cell.getStringCellValue();
                fieldNames.add(stringCellValue);
            }
        }
        JSONObject jsonField = getJsonField(aClass);
        for (int i = 1; i <= rowNo; i++) {
            row=sheet.getRow(i);
            JSONObject jsonObject = new JSONObject();
            for (int j = 0; j < fieldNames.size(); j++) {
                Cell cell = row.getCell(j);
                if (cell!=null){
                    Object value = null;
                    CellType cellTypeEnum = cell.getCellTypeEnum();
                    if (cellTypeEnum.equals(CellType.STRING)){
                        value = cell.getStringCellValue();
                        try {
                            value= simpleDateFormat.parse(value.toString());
                        } catch (ParseException e) {
                            try {
                                value= sdf1.parse(value.toString());
                            } catch (ParseException e1) {
                                try {
                                    value= sdf2.parse(value.toString());
                                } catch (ParseException e2) {
                                    try {
                                        value= sdf3.parse(value.toString());
                                    } catch (ParseException e3) {
                                    }
                                }
                            }
                        }
                    }
                    else  if (cellTypeEnum.equals(CellType.NUMERIC)){
                        value = cell.getNumericCellValue();
                    }
                    else  if (cellTypeEnum.equals(CellType.BOOLEAN)){
                        value = cell.getBooleanCellValue();
                    }
                    String string = jsonField.getString(fieldNames.get(j));
                    jsonObject.put(string,value);
                }
            }
            array.add(jsonObject);
        }
        return array;
    }

    /**
     * 创建有密码保护的excel文件
     * @param aClass
     * @param list
     * @param fileName
     * @param password
     * @param <T>
     * @return
     * @throws Exception
     */
    public static<T> File createXlsxExcel(Class<T> aClass, List<T> list, String fileName,String password) throws Exception{
        // 创建一个webbook,对应一个Excel文件
        Workbook wb = new XSSFWorkbook();
        CellStyle textType = wb.createCellStyle();
        CellStyle dateType = wb.createCellStyle();
        DataFormat dataFormat = wb.createDataFormat();
        textType.setDataFormat(dataFormat.getFormat("@"));
        dateType.setDataFormat(dataFormat.getFormat("yyyy年m月d日"));
        // 在webbook中添加一个sheet,对应Excel文件中的sheet
        Sheet sheet = wb.createSheet("sheet1");
        // 在sheet中添加表头第0行,注意老版本poi对Excel的行数列数有限制short
        Row row = sheet.createRow(0);
        // 添加标题行
        Cell cell = null;
        Field[] fields = aClass.getDeclaredFields();
        List<Field> excelField = new ArrayList<>();
        int excelNo=0;
        for (int i = 0; i < fields.length; i++) {
            ExcelField annotation = fields[i].getAnnotation(ExcelField.class);
            if (annotation!=null){
                if (annotation.ignore()==true){
                    continue;
                }
                else {
                    excelField.add(fields[i]);
                    // 获取行内对应单元格
                    cell = row.createCell(excelNo++);
                    // 单元格赋值
                    String value = annotation.value();
                    if (value.equals("")){
                        cell.setCellValue(fields[i].getName());
                    }
                    else {
                        cell.setCellValue(value);
                    }
                }
            }
            else {
                cell = row.createCell(excelNo++);
                cell.setCellValue(fields[i].getName());
                excelField.add(fields[i]);
            }
        }
        // 写入实体数据,实际应用中这些数据从数据库得到,list中字符串的顺序必须和数组strArray中的顺序一致
        int i = 0;
        for (int j = 0; j < list.size(); j++) {
            T t = list.get(i);
            i++;
            row = sheet.createRow(i );
            // 添加数据行
            //数据转为Json
            String json= JSON.toJSONString(t);//关键
            JSONObject parse = (JSONObject) JSONObject.parse(json);
            for (int z = 0; z < excelField.size(); z++) {
                Field field=excelField.get(z);
                ExcelField annotation = field.getAnnotation(ExcelField.class);
                boolean ignore =false;
                if (annotation!=null){
                    ignore = annotation.ignore();
                }
                if (!ignore){
                    cell = row.createCell(z);
                    cell.setCellStyle(textType);
                    // 获取行内对应单元格
                    String name = field.getName();
                    Object o = parse.get(name);
                    // 单元格赋值
                    if (o instanceof Long){
                        long o1 = (long) o;
                        Date date = null;
                        SimpleDateFormat simpleDateFormat = null;
                        try {
                            date = new Date();
                            date.setTime(o1);
                            simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                            cell.setCellValue(simpleDateFormat.format(date));
                        } catch (Exception e) {
                            e.printStackTrace();
                            cell.setCellValue(o1);
                        }

                    }
                    else if (o instanceof String){
                        cell.setCellValue((String) o);
                    }
                    else if (o instanceof Double){
                        cell.setCellValue((double) o);
                    }
                    else if (o instanceof Boolean){
                        cell.setCellValue((boolean) o);
                    }
                }

            }
        }
        // 第六步,将文件存到指定位置
        FileOutputStream fout = new FileOutputStream(fileName);
        try {
            wb.write(fout);
            fout.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        finally {
            fout.close();
        }
        //设置打开保护密码
        File file = new File(fileName);
        POIFSFileSystem fs = new POIFSFileSystem();
        EncryptionInfo encryptionInfo = new EncryptionInfo(EncryptionMode.agile);
        Encryptor enc = encryptionInfo.getEncryptor();
        enc.confirmPassword(password);
        OPCPackage opc = OPCPackage.open(file, PackageAccess.READ_WRITE);
        OutputStream os = enc.getDataStream(fs);
        opc.save(os);
        opc.close();
        FileOutputStream fos = new FileOutputStream(file);
        fs.writeFilesystem(fos);
        fos.close();
        return new File(fileName);
    }

    /**
     * 打开有密码保护的excel文件
     * @param aClass
     * @param file
     * @param password
     * @param <T>
     * @return
     */
    public static<T> JSONArray readXlsxExcel(Class<T> aClass,File file,String password) throws IOException, InvalidFormatException {
        JSONArray array = new JSONArray();
        Workbook work = WorkbookFactory.create(file, password);
//            Workbook work = new XSSFWorkbook(new FileInputStream(file.getAbsolutePath()));// 得到这个excel表格对象
        Sheet sheet = work.getSheetAt(0);//得到第一个sheet
        int rowNo = sheet.getLastRowNum(); //得到行数
        //获取首行列头
        Row row = sheet.getRow(0);
        short lastCellNum = row.getLastCellNum();
        List<String> fieldNames = new ArrayList<>();
        for (int i = 0; i < lastCellNum; i++) {
            Cell cell = row.getCell(i);
            if (cell!=null){
                String stringCellValue = cell.getStringCellValue();
                fieldNames.add(stringCellValue);
            }
        }
        JSONObject jsonField = getJsonField(aClass);
        for (int i = 1; i <= rowNo; i++) {
            row=sheet.getRow(i);
            JSONObject jsonObject = new JSONObject();
            for (int j = 0; j < fieldNames.size(); j++) {
                Cell cell = row.getCell(j);
                if (cell!=null){
                    Object value = null;
                    CellType cellTypeEnum = cell.getCellTypeEnum();
                    if (cellTypeEnum.equals(CellType.STRING)){
                        value = cell.getStringCellValue();
                        try {
                            value= simpleDateFormat.parse(value.toString());
                        } catch (ParseException e) {
                            try {
                                value= sdf1.parse(value.toString());
                            } catch (ParseException e1) {
                                try {
                                    value= sdf2.parse(value.toString());
                                } catch (ParseException e2) {
                                    try {
                                        value= sdf3.parse(value.toString());
                                    } catch (ParseException e3) {
                                    }
                                }
                            }
                        }
                    }
                    else  if (cellTypeEnum.equals(CellType.NUMERIC)){
                        value = cell.getNumericCellValue();
                    }
                    else  if (cellTypeEnum.equals(CellType.BOOLEAN)){
                        value = cell.getBooleanCellValue();
                    }
                    String string = jsonField.getString(fieldNames.get(j));
                    jsonObject.put(string,value);
                }
            }
            array.add(jsonObject);
        }
        return array;
    }
}




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值