根据实体excel导入导出百万数据,可修改表头名称

news2024/10/5 0:46:02

提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档

文章目录

  • 表格导入导出实现效果展示
    • 根据实体类导出模板
    • 读取表格数据
    • 导出数据为excel
    • 进阶:修改表格导出的列头
  • controller示例
  • 工具类
  • 测试实体
  • 实体注解
  • maven依赖


表格导入导出实现效果展示

根据实体类导出模板

所有对excel都是根据实体类进行操作

在这里插入图片描述

根据实体导出的excel模板展示
在这里插入图片描述

读取表格数据

在这里插入图片描述

读取结果返回,和表格上传数据一致
在这里插入图片描述

导出数据为excel

也支持将已有的数据导出为表格
在这里插入图片描述

进阶:修改表格导出的列头

部分情况,表头需要为中文,可以使用注解,对表格进行标注,导出的模板和导出的数据列头就是注解的内容了
在这里插入图片描述
在这里插入图片描述

controller示例

一下示例代码实现了表格模板导出、数据导出、数据读取和百万数据读取

package com.mabo.controller;


import com.alibaba.fastjson.JSONArray;
import com.mabo.entity.ChatInfo;
import com.mabo.util.ExcelHSSFUtil;
import com.monitorjbl.xlsx.StreamingReader;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.util.IOUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.io.File;
/**
 * TODO your comment
 *
 * @author Yujiaqi
 * @date 2020/12/2 19:20
 */
@Slf4j
@RestController
@RequestMapping("/excel")
public class ExcelController {

    /**
     * 读取excel
     */
    @PostMapping("/upload")
    public Object upload(MultipartHttpServletRequest file) throws Exception {
        MultipartFile file1 = file.getFile("file");
        byte[] bytes = IOUtils.toByteArray(file1.getInputStream());
        File excelFile = new File("test1.xlsx");
        FileOutputStream fos = new FileOutputStream(excelFile);
        fos.write(bytes);
        fos.close();
        JSONArray  jsonArray = ExcelHSSFUtil.readXlsxExcel(ChatInfo.class, excelFile);
        return jsonArray;
    }
    /**
     * 下载excel模板
     */
    @GetMapping("/download")
    public void download(HttpServletResponse response) throws Exception {
        String fileName="downloadModel.xlsx";
        fileName = URLEncoder.encode(fileName,"UTF-8");
        File file=new File(fileName);
        file = ExcelHSSFUtil.createXlsxExcel(ChatInfo.class, new ArrayList<>(), file.getAbsolutePath());
        // 以流的形式下载文件。
        InputStream fis = null;
        try {
            fis = new BufferedInputStream(new FileInputStream(file.getAbsoluteFile()));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        byte[] buffer = new byte[fis.available()];
        fis.read(buffer);
        fis.close();
        // 清空response
        response.reset();
        // 设置response的Header
        response.addHeader("Content-Disposition", "attachment;filename=" + new String(file.getName().getBytes()));
        response.addHeader("Content-Length", "" + file.length());
        OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
        response.setContentType("application/octet-stream;charset=utf-8");
        toClient.write(buffer);
        toClient.flush();
        toClient.close();
    }

    /**
     * 超大数据量上传
     * @param file
     * @return
     * @throws Exception
     */
    @PostMapping("/uploadBatch")
    public Object uploadBatch(MultipartHttpServletRequest file) throws Exception {
        MultipartFile file1 = file.getFile("file");
        byte[] bytes = IOUtils.toByteArray(file1.getInputStream());
        File excelFile = new File("test1.xlsx");
        FileOutputStream fos = new FileOutputStream(excelFile);
        fos.write(bytes);
        fos.close();

        InputStream inputStream1 = new FileInputStream(excelFile);
        JSONArray jsonArray = null;
        Workbook work= StreamingReader.builder()
                .rowCacheSize(100)  //缓存到内存中的行数,默认是10
                .bufferSize(4096)  //读取资源时,缓存到内存的字节大小,默认是1024
                .open(inputStream1);
        Sheet sheet = work.getSheetAt(0);//得到第一个sheet
        int excelSize = sheet.getLastRowNum();
        int max =3;
        if (excelSize < max) {
            jsonArray = ExcelHSSFUtil.readXlsxExcel(ChatInfo.class, excelFile);
            System.out.println(jsonArray);
        }else {
            //大数据进行多线程处理,并且直接返回数据
            int size=max;
            for (int i = 1; i < excelSize; ) {
                log.info("当前为第" + i);
                jsonArray = ExcelHSSFUtil.readXlsxExcelCache(ChatInfo.class, excelFile, i, size);
                System.out.println(jsonArray);
                i+=max;
                if (i+max>excelSize){
                    jsonArray = ExcelHSSFUtil.readXlsxExcelCache(ChatInfo.class, excelFile,i,excelSize-i);
                    System.out.println(jsonArray);
                }
            }

        }
        return jsonArray;
    }



    /**
     * 下载excel批量数据
     */
    @GetMapping("/downloadBatch")
    public void downloadBatch(HttpServletResponse response) throws Exception {
        String fileName="downloadBatch.xlsx";
        fileName = URLEncoder.encode(fileName,"UTF-8");
        File file=new File(fileName);
        List list = new ArrayList<>();
        ChatInfo chatInfo = new ChatInfo();
        chatInfo.setMsg("1");
        chatInfo.setId("1");
        //写入业务数据
        list.add(chatInfo);
        list.add(chatInfo);
        list.add(chatInfo);
        file = ExcelHSSFUtil.createXlsxExcel(ChatInfo.class, list, file.getAbsolutePath());
        // 以流的形式下载文件。
        InputStream fis = null;
        try {
            fis = new BufferedInputStream(new FileInputStream(file.getAbsoluteFile()));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        byte[] buffer = new byte[fis.available()];
        fis.read(buffer);
        fis.close();
        // 清空response
        response.reset();
        // 设置response的Header
        response.addHeader("Content-Disposition", "attachment;filename=" + new String(file.getName().getBytes()));
        response.addHeader("Content-Length", "" + file.length());
        OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
        response.setContentType("application/octet-stream;charset=utf-8");
        toClient.write(buffer);
        toClient.flush();
        toClient.close();
    }

}

工具类

package com.mabo.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.mabo.annotation.ExcelField;
import com.monitorjbl.xlsx.StreamingReader;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.*;
import java.lang.reflect.Field;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Slf4j
public class ExcelHSSFUtil<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日");

    public static <T> File create(Class<T> aClass, List<T> list, String fileName) throws IOException {
        // 创建一个webbook,对应一个Excel文件
        HSSFWorkbook wb = new HSSFWorkbook();
        HSSFCellStyle textType = wb.createCellStyle();
        HSSFCellStyle dateType = wb.createCellStyle();
        HSSFDataFormat format = wb.createDataFormat();
        textType.setDataFormat(format.getFormat("@"));
        dateType.setDataFormat(format.getFormat("yyyy年m月d日"));

        // 在webbook中添加一个sheet,对应Excel文件中的sheet
        HSSFSheet sheet = wb.createSheet("sheet1");
        // 在sheet中添加表头第0行,注意老版本poi对Excel的行数列数有限制short
        HSSFRow row = sheet.createRow(0);
        // 添加标题行
        HSSFCell 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());
            }
        }
        // 写入实体数据,实际应用中这些数据从数据库得到,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);
    }

    /**
     * @Description : 读取excel为实体集合
     * @Author : mabo
     */

    public static <T> JSONArray readExcel(Class<T> aClass, File file) {
        JSONArray array = new JSONArray();
        try {
            FileInputStream fileInputStream = new FileInputStream(file.getAbsolutePath());
            HSSFWorkbook work = new HSSFWorkbook(fileInputStream);// 得到这个excel表格对象
            HSSFSheet sheet = work.getSheetAt(0); //得到第一个sheet
            int rowNo = sheet.getLastRowNum(); //得到行数
            //获取首行列头
            HSSFRow row = sheet.getRow(0);
            short lastCellNum = row.getLastCellNum();
            List<String> fieldNames = new ArrayList<>();
            for (int i = 0; i < lastCellNum; i++) {
                HSSFCell 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++) {
                    HSSFCell 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);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return array;
    }

    /**
     * @Description : 获取表格列头和实体的对应关系
     * @Author : mabo
     */
    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;
    }


    /**
     * @Description : 生成xlsx格式表格文件,可上传的数据量更大
     */

    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 SXSSFWorkbook(3000);
        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 {
                excelField.add(fields[i]);
                cell = row.createCell(excelNo++);
                cell.setCellValue(fields[i].getName());
            }
        }
        // 写入实体数据,实际应用中这些数据从数据库得到,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);
    }

    public static <T> JSONArray readXlsxExcel(Class<T> aClass, File file) {
        JSONArray array = new JSONArray();
        try {
            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);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return array;
    }

    public static <T> JSONArray readXlsxExcel(Class<T> aClass, File file, int start, int size) {
        JSONArray array = new JSONArray();
        try {
            Workbook work = new XSSFWorkbook(new FileInputStream(file.getAbsolutePath()));// 得到这个excel表格对象
            Sheet sheet = work.getSheetAt(0);//得到第一个sheet
            int rowNo = sheet.getLastRowNum(); //得到行数
            if (rowNo > start + size) {
                rowNo = start + size;
            }
            //获取首行列头
            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);
            //从数据行开始
            start++;
            for (int i = start; 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);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return array;
    }

    public static <T> JSONArray readXlsxExcelCache(Class<T> aClass, File file, int start, int size) throws FileNotFoundException {
        InputStream inputStream1 = new FileInputStream(file);
        Workbook work = StreamingReader.builder()
                .rowCacheSize(100)  //缓存到内存中的行数,默认是10
                .bufferSize(4096)  //读取资源时,缓存到内存的字节大小,默认是1024
                .open(inputStream1);
        Sheet sheet = work.getSheetAt(0);//得到第一个sheet
        int excelSize = sheet.getLastRowNum();
        //大数据进行多线程处理,并且直接返回数据
        log.info("当前数据量大小为" + excelSize);
        List<String> fieldNames = new ArrayList<>();
        JSONArray array = new JSONArray();
        JSONObject jsonField = ExcelHSSFUtil.getJsonField(aClass);
        for (Row row : sheet) {
            if (row.getRowNum() == 0) {
                short lastCellNum = row.getLastCellNum();
                for (int i = 0; i < lastCellNum; i++) {
                    Cell cell = row.getCell(i);
                    if (cell != null) {
                        String stringCellValue = cell.getStringCellValue();
                        fieldNames.add(stringCellValue);
                    }
                }
            }
            int maxSize = start + size;
            if (row.getRowNum() >= start && row.getRowNum()<maxSize) { //从设定的行开始取值
                //对当前行逐列进行循环取值
                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);
            }
            if (row.getRowNum()>maxSize){
                break;
            }
        }
        return array;
    }


    public static int getExcelSize(File file) throws IOException {
//        Workbook work = new XSSFWorkbook(new FileInputStream(file.getAbsolutePath()));// 得到这个excel表格对象
//        Sheet sheet = work.getSheetAt(0);//得到第一个sheet
//        return  sheet.getLastRowNum(); //得到行数
        InputStream inputStream1 = new FileInputStream(file);
        Workbook work= StreamingReader.builder()
                .rowCacheSize(100)  //缓存到内存中的行数,默认是10
                .bufferSize(4096)  //读取资源时,缓存到内存的字节大小,默认是1024
                .open(inputStream1);
        Sheet sheet = work.getSheetAt(0);//得到第一个sheet
        int excelSize = sheet.getLastRowNum();
        return excelSize;
    }

    /**
     * @Description : 生成xlsx格式表格文件,可上传的数据量更大
     */

    public static <T> File createXlsxExcelCache(Class<T> aClass, List<T> list, String fileName,int startRow) throws Exception {
        // 创建一个webbook,对应一个Excel文件
//        File file = new File(fileName);
//        XSSFWorkbook tplWorkBook = new XSSFWorkbook(new FileInputStream(file));
        Workbook wb = new SXSSFWorkbook( 3000);
//
//        InputStream inputStream1 = new FileInputStream(file);
//        Workbook wb =   new XSSFWorkbook(inputStream1);
//        wb = new SXSSFWorkbook(wb,3000);
        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
        List<Field> excelField = new ArrayList<>();
        Row row =null;
        Cell cell = null;
        if (startRow==0){
            row = sheet.createRow(0);
            // 添加标题行
            Field[] fields = aClass.getDeclaredFields();
            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 {
                    excelField.add(fields[i]);
                    cell = row.createCell(excelNo++);
                    cell.setCellValue(fields[i].getName());
                }
            }
        }else {
            // 不添加标题行,只获取数
            Field[] fields = aClass.getDeclaredFields();
            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]);
                    }
                } else {
                    excelField.add(fields[i]);
                }
            }
        }

        // 写入实体数据,实际应用中这些数据从数据库得到,list中字符串的顺序必须和数组strArray中的顺序一致
        int i = startRow;
        for (int j = 0; j < list.size(); j++) {
            T t = list.get(j);
            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);
    }

    public static <T> File appendExcelDataWithCache(Class<T> aClass, List<T> list, String fileName,int startRow) throws Exception {
        FileInputStream input = new FileInputStream(fileName);
        XSSFWorkbook xssfWorkbook = new XSSFWorkbook(input);
        //构建SXSSF,设置模板和内存保留行数Workbook   wb = new SXSSFWorkbook(xssfWorkbook,100);
        // 创建一个webbook,对应一个Excel文件
        Workbook wb = new SXSSFWorkbook( xssfWorkbook,3000);
        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.getSheet("sheet1");
        if (sheet==null){
            sheet= wb.createSheet("sheet1");
        }
        // 在sheet中添加表头第0行,注意老版本poi对Excel的行数列数有限制short
        List<Field> excelField = new ArrayList<>();
        Row row =null;
        Cell cell = null;
        if (startRow==0){
            row = sheet.createRow(0);
            // 添加标题行
            Field[] fields = aClass.getDeclaredFields();
            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 {
                    excelField.add(fields[i]);
                    cell = row.createCell(excelNo++);
                    cell.setCellValue(fields[i].getName());
                }
            }
        }else {
            // 不添加标题行,只获取数
            Field[] fields = aClass.getDeclaredFields();
            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]);
                    }
                } else {
                    excelField.add(fields[i]);
                }
            }
        }

        // 写入实体数据,实际应用中这些数据从数据库得到,list中字符串的顺序必须和数组strArray中的顺序一致
        int i = startRow;
        for (int j = 0; j < list.size(); j++) {
            T t = list.get(j);
            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);
    }


    /**
     * @Description : 向excel中追加数据,不影响原来数据
     * @Author : mabo
     */
    public static <T> Workbook appendExcelDataWithCache( Workbook wb,Class<T> aClass, List<T> list,int startRow) throws Exception {
        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.getSheet("sheet1");
        if (sheet==null){
            sheet= wb.createSheet("sheet1");
        }
        // 在sheet中添加表头第0行,注意老版本poi对Excel的行数列数有限制short
        List<Field> excelField = new ArrayList<>();
        Row row =null;
        Cell cell = null;
        if (startRow==0){
            row = sheet.createRow(0);
            // 添加标题行
            Field[] fields = aClass.getDeclaredFields();
            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 {
                    excelField.add(fields[i]);
                    cell = row.createCell(excelNo++);
                    cell.setCellValue(fields[i].getName());
                }
            }
        }else {
            // 不添加标题行,只获取数
            Field[] fields = aClass.getDeclaredFields();
            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]);
                    }
                } else {
                    excelField.add(fields[i]);
                }
            }
        }

        // 写入实体数据,实际应用中这些数据从数据库得到,list中字符串的顺序必须和数组strArray中的顺序一致
        int i = startRow;
        for (int j = 0; j < list.size(); j++) {
            T t = list.get(j);
            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);
                    }
                }

            }
        }
        return wb;
    }
}


测试实体

package com.mabo.entity;

import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import com.mabo.annotation.ExcelField;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import java.io.Serializable;
import java.util.Date;

/**
 * (ChatInfo)实体类
 *
 * @author makejava
 * @since 2022-08-01 16:18:08
 */
@Data
public class ChatInfo implements Serializable {
    /**
     * 主键
     */
    @ExcelField("主键id")
    private String id;
    /**
     * 消息
     */
    @ExcelField("消息")
    private String msg;

}


实体注解

package com.mabo.annotation;

import java.lang.annotation.*;

@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface ExcelField {
    String value() default "";
    boolean ignore() default false;
}

maven依赖

<dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>5.3.22</version>
        </dependency>


        <!-- 07版本以后的格式 .xlsx -->
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>3.17</version>
        </dependency>
        <!-- 读取大量excel数据时使用 -->
        <dependency>
            <groupId>com.monitorjbl</groupId>
            <artifactId>xlsx-streamer</artifactId>
            <version>2.1.0</version>
        </dependency>

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/642576.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

基于SpringBoot+微信小程序的医院预约叫号小程序

✌全网粉丝20W,csdn特邀作者、博客专家、CSDN新星计划导师、java领域优质创作者,博客之星、掘金/华为云/阿里云/InfoQ等平台优质作者、专注于Java技术领域和毕业项目实战✌ &#x1f345;文末获取项目下载方式&#x1f345; 一、项目背景介绍&#xff1a; 该项目是基于uniappWe…

加密软件VMProtect教程:使用Windows、Net 、UNIX 秘钥生成器

VMProtect是新一代软件保护实用程序。VMProtect支持德尔菲、Borland C Builder、Visual C/C、Visual Basic&#xff08;本机&#xff09;、Virtual Pascal和XCode编译器。 同时&#xff0c;VMProtect有一个内置的反汇编程序&#xff0c;可以与Windows和Mac OS X可执行文件一起…

VMware虚拟机和主机传输文件

原文链接 虚拟机为Linux系统 使用vm-tools即可。 卸载旧工具&#xff1a; vmware-uninstall-tools.pl安装新工具&#xff1a; apt-get install open-vm-tools-desktop重启系统&#xff1a; reboot此时可以使用CtrlC、CtrlV的方式在主机和Linux虚拟机之间传输文件。 虚拟…

【网络原理】TCP协议如何实现可靠传输(确认应答机制)

&#x1f94a;作者&#xff1a;一只爱打拳的程序猿&#xff0c;Java领域新星创作者&#xff0c;CSDN、阿里云社区优质创作者。 &#x1f93c;专栏收录于&#xff1a;计算机网络原理 本篇主要讲解&#xff1a;TCP协议段格式&#xff0c;TCP的序列号&#xff0c;SYN、ACK标志位&a…

操作系统(王道)

1.1_1_操作系统概念 裸机&#xff08;硬件只听得懂二进制指令&#xff09;——>操作系统&#xff08;属于软件&#xff0c;提供良好交互界面&#xff09;——>应用软件——>用户使用 操作系统是指控制和管理整个计算机系统的硬件和软件资源&#xff0c;并合理地组织…

Python技术自学的方式

Python是一种高级编程语言&#xff0c;被广泛用于软件开发、数据分析、人工智能和科学计算等领域。它于1991年由Guido van Rossum创建&#xff0c;并且其简洁、易读的语法以及丰富的标准库使得它成为了初学者和专业开发人员的首选语言之一。 一、Python技术介绍 学习Python技术…

css响应式布局

这里写自定义目录标题 1.效果展示2.使用grid布局3.使用flex布局 1.效果展示 2.使用grid布局 <!DOCTYPE html> <html><head><meta name"viewport" content"widthdevice-width, initial-scale1.0, maximum-scale1.0, user-scalableno"…

ASEMI代理安森美MOS管FQL40N50参数,FQL40N50描述

编辑-Z FQL40N50参数描述&#xff1a; 型号&#xff1a;FQL40N50 漏源电压VDSS&#xff1a;500V 漏极电流ID&#xff1a;40A 漏极电流-脉冲IDM&#xff1a;160A 栅极-源极电压VGSS&#xff1a;30V 功耗PD&#xff1a;460W 操作和储存温度范围TJ, TSTG&#xff1a;-55 t…

Rust in Action笔记 第六章 内存

Option<T>类型在Rust中使用了空指针优化&#xff08;null pointer optimization&#xff09;来保证该类型在编译后的二进制文件中占用0个字节。None变量是通过一个空指针null pointer来表示&#xff1b;内存地址、指针、引用的区别&#xff0c;内存地址是指在内存中的一个…

SpringBatch从入门到实战(三):多步骤控制

一&#xff1a;if else案例 案例&#xff1a;如果开始步骤成功了就执行成功步骤&#xff0c;否则执行失败步骤。 // 伪代码 String exitStatus helloWorldJob(); if("FAILED".equals(exitStatus)){failStep(); }else{successStep(); }Configuration public class …

01 面向对象方法的概念

面向对象方法的概念 1、什么是面向对象? 面向对象不仅仅是一种程序开发方法 使用面向对象程序设计语言 使用对象、类、继承、封装、消息等基本概念进 行编程 面向对象是一种软件方法学 如何看待软件系统与现实世界的关系 以什么观点进行求解 如何进行系统构造 2、面向对象方…

chatgpt赋能python:Python导入自己写的包详解

Python导入自己写的包详解 在Python中&#xff0c;我们可以将代码封装成包来重复利用&#xff0c;也可以将自己写的包分享给其他人使用。但是&#xff0c;在使用自己写的包时&#xff0c;如何进行导入呢&#xff1f; 什么是包&#xff1f; 在Python中&#xff0c;包是一个有…

计算机网络(更新中)

本文是个人笔记&#xff0c;都是概念&#xff0c;没基础不建议看。 绪论 计算机网络的定义 最简单的定义&#xff1a;计算机网络是一些互相连接的、自治的计算机的集合因特网&#xff08;Internet&#xff09;是“网络的网络” 计算机网络的组成&#xff08;物理组成&#x…

git从http切换到ssh

git从http切换到ssh 之前项目代码git clone的http的git地址&#xff0c;后来禁用了http协议&#xff0c;只能用ssh协议。 1. 生成ssh公钥 进入Git Bash Here, 执行以下命令 ssh-keygen -m PEM -t rsa -b 4096 -C "your.emailemail.com"一直Enter直到完成。 2. 添加…

个人对几个IDE的看法

&#xff08;说明&#xff1a;本文仅表达个人看法&#xff0c;实际上文中的几个IDE功能不同&#xff0c;不能互相取代。截图上的程序均已发布&#xff09; 个人认为一款IDE在功能完整的前提下&#xff0c;应当做到操作简便。另外&#xff0c;对缩放的兼容性也会影响观感。以下…

微服务springcloud 01 sts环境,maven管理,和springcloud简介,通用模块commons

01.使用的环境是sts和maven。 02.介绍springcloud springcloud是一个大的微服务框架。 03.Spring cloud对比Dubbo Dubbo Dubbo只是一个远程调用(RPC)框架;默认基于长连接,支持多种序列化格式 Spring Cloud 框架集&#xff0c;提供了一整套微服务解决方案(全家桶);基于http调用…

【数据挖掘实战】——科大讯飞:跨境广告ROI预测

&#x1f935;‍♂️ 个人主页&#xff1a;Lingxw_w的个人主页 ✍&#x1f3fb;作者简介&#xff1a;计算机科学与技术研究生在读 &#x1f40b; 希望大家多多支持&#xff0c;我们一起进步&#xff01;&#x1f604; 如果文章对你有帮助的话&#xff0c; 欢迎评论 &#x1f4a…

云服务器上使用Docker Compose创建Redis三主三从集群

一、环境 云服务器Ubuntu20.4Dokcer 24.0.2 二、步骤 目录结构是这样&#xff1a; 绿色的目录是用来存储容器中的文件&#xff0c;不需要我们手动创建&#xff0c;将路径配置在配置文件中即可。褐色的目录和文件需要自己手动创建。 我们一共创建7个容器&#xff1a; redis…

RabbitMq消息堆积问题及惰性队列

消息堆积问题 当生产者发送消息的速度超过了消费者处理的速度&#xff0c;就会导致队列的消息堆积&#xff0c;知道队列存储消息达到上限。最早接受的消息&#xff0c;可能就会成为死信&#xff0c;会被丢弃&#xff0c;这就是消息堆积问题。 解决消费对接问题 1.增加更多的消…

Hive执行计划之只有map阶段SQL性能分析和解读

文章目录 概述1.不带函数操作的select-from-where型简单SQL1.1执行示例1.2 运行逻辑分析1.3 伪代码解释 2.带普通函数和运行操作符的普通型SQL执行计划解读2.1 执行计划解读2.2 伪代码解释逻辑 概述 可能所有的SQLboy刚接触SQL语句的时候都是select xxx from xxx where xxx。在…