使用Java导入、导出excel详解(附有封装好的工具类)

news/2024/7/21 4:54:05 标签: java, excel, 开发语言
  • 😜           :是江迪呀
  • ✒️本文关键词JavaExcel导出工具类后端
  • ☀️每日   一言:有些事情不是对的才去坚持,而是坚持了它才是对的!

前言

我们在日常开发中,一定遇到过要将数据导出为Excel的需求,那么怎么做呢?在做之前,我们需要思考下Excel的组成。Excel是由四个元素组成的分别是:WorkBook(工作簿)Sheet(工作表)Row(行)Cell(单元格),其中包含关系是从左至右,,一个WorkBook可以包含多个Sheet,一个Sheet又是由多个Row组成,一个Row是由多个Cell组成。知道这些后那么我们就使用java来将数据以Excel的方式导出。让我们一起来学习吧✏️!


一、引入Apache POI依赖

使用Java实现将数据以Excel的方式导出,需要依赖第三方的库。我们需要再pom.xml中引入下面的依赖:

java"> <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>4.1.2</version>
 </dependency>
 <dependency>
     <groupId>org.apache.poi</groupId>
     <artifactId>poi-ooxml</artifactId>
     <version>4.1.2</version>
 </dependency>

二、用法&步骤

2.1 创建Excel的元素

(1)创建WokrBook

java">Workbook workbook = new XSSFWorkbook();

(2)创建Sheet

java"> Sheet sheet = workbook.createSheet();

设置sheet的名称

javascript"> Sheet sheet = workbook.createSheet("sheet名称");

(3)创建行Row

java">Row row = sheet.createRow(0);

(4)创建单元格Cell

java">Cell cell = row.createCell(0, CellType.STRING);

可以指定单元格的类型,支持的类型有下面7种:

java">    _NONE(-1),
    NUMERIC(0),
    STRING(1),
    //公式
    FORMULA(2),
    BLANK(3),
    //布尔
    BOOLEAN(4),
    ERROR(5);

(5) 填充数据

java"> cell.setCellValue("苹果");

2.3 样式和字体

如果我们需要导出的Excel美观一些,如设置字体的样式加粗颜色大小等等,就需要创建样式和字体。
创建样式:

javascript">CellStyle cellStyle = workbook.createCellStyle();

(1)左右垂直居中

java">//左右居中
excelTitleStyle.setAlignment(HorizontalAlignment.CENTER);
// 设置垂直居中
excelTitleStyle.setVerticalAlignment(VerticalAlignment.CENTER);

(2)字体加粗、颜色

创建加粗样式并设置到CellStyle 中:

java">Font font = workbook.createFont();
//字体颜色为红色
font.setColor(IndexedColors.RED.getIndex());
//字体加粗
font.setBold(true);
cellStyle.setFont(font);

指定Cell单元格使用该样式:

javascript">cell.setCellStyle(style);

(3)调整列宽和高

java">Sheet sheet = workbook.createSheet();
//自动调整列的宽度来适应内容
sheet.autoSizeColumn(int column); 
// 设置列的宽度
sheet.setColumnWidth(2, 20 * 256); 

autoSizeColumn()传递的参数就是要设置的列索引。setColumnWidth()第一个参数是要设置的列索引,第二参数是具体的宽度值,宽度 = 字符个数 * 256(例如20个字符的宽度就是20 * 256)

(4)倾斜、下划线

javascript">Font font = workbook.createFont();
font.setItalic(boolean italic); 设置倾斜
font.setUnderline(byte underline); 设置下划线

2.4 进阶用法

(1)合并单元格

java">Workbook workbook = new XSSFWorkbook();
Sheet sheet = workbook.createSheet(fileName);
sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, 5));
  • CellRangeAddress()方法四个参数分别是fristRow:起始行、lastRow:结束行、fristCol:起始列、lastCol:结束列。
    如果你想合并从第一行到第二行从一列到第十列的单元格(一共合并20格),那么就是CellRangeAddress(0,1,0,10)

(2)字段必填

java">//创建数据验证
DataValidationHelper dvHelper = sheet.getDataValidationHelper();
//创建要添加校验的单元格对象
CellRangeAddressList addressList = new CellRangeAddressList(0, 0, 0, 10);
//创建必填校验规则
DataValidationConstraint constraint = validationHelper.createCustomConstraint("NOT(ISBLANK(A1))");
//设置校验
DataValidation validation = dvHelper.createValidation(constraint, addressList);
//校验不通过 提示
validation.setShowErrorBox(true);
sheet.addValidationData(validation);
  • CellRangeAddressList()方法传递四个参数,分别是:fristRow:起始行、lastRow:结束行、fristCol:起始列、lastCol:结束列。CellRangeAddressList(0, 0, 0, 10)表示的就是给第一行从第一列开始到第十列一共十个单元格添加数据校验。

(3)添加公式

  • SUM:求和函数
java">//创建SUM公式
FormulaEvaluator evaluator = workbook.getCreationHelper().createFormulaEvaluator();
Cell sumCell = row.createCell(0);
sumCell.setCellFormula("SUM(A1:A10)");
//计算SUM公式结果
Cell sumResultCell = row.createCell(1);
sumResultCell.setCellValue(evaluator.evaluate(sumCell).getNumberValue());
  • AVERAGE:平均数函数
java">//创建AVERAGE公式
FormulaEvaluator evaluator = workbook.getCreationHelper().createFormulaEvaluator();
Cell averageCell = row.createCell(0);
averageCell.setCellFormula("AVERAGE(A1:A10)");

//计算AVERAGE公式结果
Cell averageResultCell = row.createCell(1);
averageResultCell.setCellValue(evaluator.evaluate(averageCell).getNumberValue());
  • COUNT:计数函数
java">//创建COUNT公式
FormulaEvaluator evaluator = workbook.getCreationHelper().createFormulaEvaluator();
Cell countCell = row.createCell(0);
countCell.setCellFormula("COUNT(A1:A10)");

//计算COUNT公式结果
Cell countResultCell = row.createCell(1);
countResultCell.setCellValue(evaluator.evaluate(countCell).getNumberValue());

  • IF:条件函数
java">//创建IF公式
FormulaEvaluator evaluator = workbook.getCreationHelper().createFormulaEvaluator();
Cell ifCell = row.createCell(0);
ifCell.setCellFormula("IF(A1>B1,\"Yes\",\"No\")");

//计算IF公式结果
Cell ifResultCell = row.createCell(1);
ifResultCell.setCellValue(evaluator.evaluate(ifCell).getStringValue());

  • CONCATENATE:连接函数
java">//创建CONCATENATE公式
FormulaEvaluator evaluator = workbook.getCreationHelper().createFormulaEvaluator();
Cell concatenateCell = row.createCell(0);
concatenateCell.setCellFormula("CONCATENATE(A1,\" \",B1)");

//计算CONCATENATE公式结果
Cell concatenateResultCell = row.createCell(1);
concatenateResultCell.setCellValue(evaluator.evaluate(concatenateCell).getStringValue());

(4)下拉选择

java">//下拉值
private List<String> grade = Arrays.asList("高", "中", "低");
(此处省略n行代码)
Sheet sheet = workbook.createSheet("sheet");
DataValidation dataValidation = this.addPullDownConstraint(i, sheet, grade );
sheet.addValidationData(dataValidation);

(5)设置单元格的数据类型

  • 数字格式
javascript">// 设置单元格样式 - 数字格式
CellStyle numberCellStyle = workbook.createCellStyle();
numberCellStyle.setDataFormat(workbook.createDataFormat().getFormat("#,##0.00"));
//指定单元格
Row row = sheet.createRow(0);
Cell cell = row.createCell(0);
cell.setCellStyle(numberCellStyle);
  • 日期格式
javascript">// 设置单元格样式 - 日期格式
CellStyle dateCellStyle = workbook.createCellStyle();
dateCellStyle.setDataFormat(workbook.createDataFormat().getFormat("yyyy-MM-dd"));
//指定单元格
Row row = sheet.createRow(0);
Cell cell = row.createCell(0);
cell.setCellStyle(dateCellStyle);

三、导出完整示例

下面的示例使用SpringBoot项目来演示:
pom.xml依赖:

 <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <version>2.7.5</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
            <version>2.7.5</version>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>4.1.2</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml -->
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>4.1.2</version>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.16.16</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/com.alibaba.fastjson2/fastjson2 -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>2.0.21</version>
        </dependency>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>3.12.0</version>
        </dependency>

Controller层代码:

java">package shijiangdiya.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import shijiangdiya.utils.ExportUtils;
import javax.servlet.http.HttpServletResponse;

@RestController
@RequestMapping("/sync")
public class ExportController {
}

(1)代码

java">    @Autowired
    private HttpServletResponse response;

    @PostMapping("/export")
    public void export() {
    	//模拟json数据
        String data = "[{\n" +
                "    \"studentId\": \"20210101\",\n" +
                "    \"name\": \"Alice\",\n" +
                "    \"age\": 20,\n" +
                "    \"credit\": 80\n" +
                "  },\n" +
                "  {\n" +
                "    \"studentId\": \"20210102\",\n" +
                "    \"name\": \"Bob\",\n" +
                "    \"age\": 21,\n" +
                "    \"credit\": 85\n" +
                "  },\n" +
                "  {\n" +
                "    \"studentId\": \"20210103\",\n" +
                "    \"name\": \"Charlie\",\n" +
                "    \"age\": 22,\n" +
                "    \"credit\": 90\n" +
                "  },\n" +
                "  {\n" +
                "    \"studentId\": \"20210104\",\n" +
                "    \"name\": \"David\",\n" +
                "    \"age\": 20,\n" +
                "    \"credit\": 75\n" +
                "  },\n" +
                "  {\n" +
                "    \"studentId\": \"20210105\",\n" +
                "    \"name\": \"Emily\",\n" +
                "    \"age\": 21,\n" +
                "    \"credit\": 82\n" +
                "  },\n" +
                "  {\n" +
                "    \"studentId\": \"20210106\",\n" +
                "    \"name\": \"Frank\",\n" +
                "    \"age\": 22,\n" +
                "    \"credit\": 88\n" +
                "  },\n" +
                "  {\n" +
                "    \"studentId\": \"20210107\",\n" +
                "    \"name\": \"Grace\",\n" +
                "    \"age\": 20,\n" +
                "    \"credit\": 81\n" +
                "  },\n" +
                "  {\n" +
                "    \"studentId\": \"20210108\",\n" +
                "    \"name\": \"Henry\",\n" +
                "    \"age\": 21,\n" +
                "    \"credit\": 89\n" +
                "  },\n" +
                "  {\n" +
                "    \"studentId\": \"20210109\",\n" +
                "    \"name\": \"Isaac\",\n" +
                "    \"age\": 22,\n" +
                "    \"credit\": 92\n" +
                "  },\n" +
                "  {\n" +
                "    \"studentId\": \"20210110\",\n" +
                "    \"name\": \"John\",\n" +
                "    \"age\": 20,\n" +
                "    \"credit\": 78\n" +
                "  },\n" +
                "  {\n" +
                "    \"studentId\": \"20210111\",\n" +
                "    \"name\": \"Kelly\",\n" +
                "    \"age\": 21,\n" +
                "    \"credit\": 84\n" +
                "  },\n" +
                "  {\n" +
                "    \"studentId\": \"20210112\",\n" +
                "    \"name\": \"Linda\",\n" +
                "    \"age\": 22,\n" +
                "    \"credit\": 87\n" +
                "  },\n" +
                "  {\n" +
                "    \"studentId\": \"20210113\",\n" +
                "    \"name\": \"Mike\",\n" +
                "    \"age\": 20,\n" +
                "    \"credit\": 77\n" +
                "  },\n" +
                "  {\n" +
                "    \"studentId\": \"20210114\",\n" +
                "    \"name\": \"Nancy\",\n" +
                "    \"age\": 21,\n" +
                "    \"credit\": 83\n" +
                "  },\n" +
                "  {\n" +
                "    \"studentId\": \"20210115\",\n" +
                "    \"name\": \"Oscar\",\n" +
                "    \"age\": 22,\n" +
                "    \"credit\": 91\n" +
                "  },\n" +
                "  {\n" +
                "    \"studentId\": \"20210116\",\n" +
                "    \"name\": \"Paul\",\n" +
                "    \"age\": 20,\n" +
                "    \"credit\": 76\n" +
                "  },\n" +
                "  {\n" +
                "    \"studentId\": \"20210117\",\n" +
                "    \"name\": \"Queen\",\n" +
                "    \"age\": 21,\n" +
                "    \"credit\": 86\n" +
                "  },\n" +
                "  {\n" +
                "    \"studentId\": \"20210118\",\n" +
                "    \"name\": \"Rachel\",\n" +
                "    \"age\": 22,\n" +
                "    \"credit\": 94\n" +
                "  },\n" +
                "  {\n" +
                "    \"studentId\": \"20210119\",\n" +
                "    \"name\": \"Sarah\",\n" +
                "    \"age\": 20,\n" +
                "    \"credit\": 79\n" +
                "  },\n" +
                "  {\n" +
                "    \"studentId\": \"20210120\",\n" +
                "    \"name\": \"Tom\",\n" +
                "    \"age\": 21,\n" +
                "    \"credit\": 80\n" +
                "  }\n" +
                "]\n";
        ExportUtils.exportExcel("学生信息", data, Student.class, response);
    }

(2)工具类

java">  /**
     * 数据导出
     * @param fileName 导出excel名称
     * @param data 导出的数据
     * @param c 导出数据的实体class
     * @param response 响应
     * @throws Exception
     */
    public static void exportExcel(String fileName, String data, Class<?> c, HttpServletResponse response) throws Exception {
        try {
            // 创建表头
            // 创建工作薄
            Workbook workbook = new XSSFWorkbook();
            Sheet sheet = workbook.createSheet();
            // 创建表头行
            Row rowHeader = sheet.createRow(0);
            if (c == null) {
                throw new RuntimeException("Class对象不能为空!");
            }
            Field[] declaredFields = c.getDeclaredFields();
            List<String> headerList = new ArrayList<>();
            if (declaredFields.length == 0) {
                return;
            }
            for (int i = 0; i < declaredFields.length; i++) {
                Cell cell = rowHeader.createCell(i, CellType.STRING);
                String headerName = String.valueOf(declaredFields[i].getName());
                cell.setCellValue(headerName);
                headerList.add(i, headerName);
            }
            // 填充数据
            List<?> objects = JSONObject.parseArray(data, c);
            Object obj = c.newInstance();
            if (!CollectionUtils.isEmpty(objects)) {
                for (int o = 0; o < objects.size(); o++) {
                    Row rowData = sheet.createRow(o + 1);
                    for (int i = 0; i < headerList.size(); i++) {
                        Cell cell = rowData.createCell(i);
                        Field nameField = c.getDeclaredField(headerList.get(i));
                        nameField.setAccessible(true);
                        String value = String.valueOf(nameField.get(objects.get(o)));
                        cell.setCellValue(value);
                    }
                }
            }
            response.setContentType("application/vnd.ms-excel");
            String resultFileName = URLEncoder.encode(fileName, "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + resultFileName + ";" + "filename*=utf-8''" + resultFileName);
            workbook.write(response.getOutputStream());
            workbook.close();
            response.flushBuffer();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

(2)结果

在这里插入图片描述

四、导入完整示例

(1)代码

java">@PostMapping("/import")
    public void importExcel(@RequestParam("excel") MultipartFile excel){
        Workbook workbook = null;
        try {
            workbook = WorkbookFactory.create(excel.getInputStream());
            Sheet sheet = workbook.getSheetAt(0);
            List<Student> students = new ArrayList<>();
            int i = 0;
            for (Row row : sheet) {
                Row row1 = sheet.getRow(i + 1);
                if(row1 != null){
                    Student data = new Student();
                    data.setStudentId(Integer.parseInt(row1.getCell(0).getStringCellValue()));
                    data.setName(row1.getCell(1).getStringCellValue());
                    data.setAge(Integer.parseInt(row1.getCell(2).getStringCellValue()));
                    data.setCredit(Integer.parseInt(row1.getCell(3).getStringCellValue()));
                    students.add(data);
                }
            }
            System.out.println(students);
            workbook.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

(2)工具类

java"> /**
     * 导入
     * @param workbook 工作簿
     * @param c 实体类
     * @return 实体类集合
     */
    public static <T> List<T> importExcel(Workbook workbook,Class<?> c){
        List<T> dataList = new ArrayList<>();
        try {
            Sheet sheet = workbook.getSheetAt(0);
            int i = 0;
            T o = null;
            for (Row row : sheet) {
                Row row1 = sheet.getRow(i + 1);
                if(row1 != null){
                    o = (T) c.newInstance();
                    Field[] declaredFields = c.getDeclaredFields();
                    for (int i1 = 0; i1 < declaredFields.length; i1++) {
                        String name = declaredFields[i1].getName();
                        Field declaredField1 = o.getClass().getDeclaredField(name);
                        declaredField1.setAccessible(true);
                        Cell cell = row1.getCell(i1);
                        String type = declaredFields[i1].getType().getName();
                        String value = String.valueOf(cell);
                        if(StringUtils.equals(type,"int") || StringUtils.equals(type,"Integer")){
                            declaredField1.set(o,Integer.parseInt(value));
                        } else if(StringUtils.equals(type,"java.lang.String") || StringUtils.equals(type,"char") || StringUtils.equals(type,"Character") ||
                                StringUtils.equals(type,"byte") || StringUtils.equals(type,"Byte")){
                            declaredField1.set(o,value);
                        } else if(StringUtils.equals(type,"boolean") || StringUtils.equals(type,"Boolean")){
                            declaredField1.set(o,Boolean.valueOf(value));
                        } else if(StringUtils.equals(type,"double") || StringUtils.equals(type,"Double")){
                            declaredField1.set(o,Double.valueOf(value));
                        } else if (StringUtils.equals(type,"long") || StringUtils.equals(type,"Long")) {
                            declaredField1.set(o,Long.valueOf(value));
                        } else if(StringUtils.equals(type,"short") || StringUtils.equals(type,"Short")){
                            declaredField1.set(o,Short.valueOf(value));
                        } else if(StringUtils.equals(type,"float") || StringUtils.equals(type,"Float")){
                            declaredField1.set(o,Float.valueOf(value));
                        }
                    }
                }
                dataList.add(o);
            }
            workbook.close();
            return dataList;
        }catch (Exception e){
            e.printStackTrace();
        }
        return dataList;
    }

注意:导入工具类仅限Java的八大基础数据类型String类型。如果还有其他类型需要自己扩展。

(3)结果

学生信息集合:
在这里插入图片描述


http://www.niftyadmin.cn/n/166208.html

相关文章

Python列表

Python列表 Python是一种高级编程语言&#xff0c;它包含了许多数据结构&#xff0c;其中最常用的是列表。列表是一种非常重要的数据结构&#xff0c;它允许我们存储和使用一组有序的元素。Python的列表非常灵活和强大&#xff0c;可以用于各种类型的数据和应用。在本篇文章中…

windows10或ubuntu系统下,中文音频转汉字

目录 1.安装开源库&#xff1b; 2.下载中文model(也可以先不下载) 3.使用转换 4. 效果展示 &#xff08;唠嗑&#xff09;出发背景&#xff1a;我听到一段长达一小时的音频&#xff0c;里面讲的特别好&#xff0c;我就想下载转成文字再看看&#xff0c;可是用软件超1分钟就要…

百度生成式AI产品文心一言邀你体验AI创作新奇迹:百度CEO李彦宏详细透露三大产业将会带来机遇(文末附文心一言个人用户体验测试邀请码获取方法,亲测有效)

百度生成式AI产品文心一言邀你体验AI创作新奇迹中国版ChatGPT上线发布强大中文理解能力超强的数理推算能力智能文学创作、商业文案创作图片、视频智能生成中国生成式AI三大产业机会新型云计算公司行业模型精调公司应用服务提供商总结获取文心一言邀请码方法中国版ChatGPT上线发…

Matlab论文插图绘制模板第82期—箭头图(quiver)

在之前的文章中&#xff0c;分享了Matlab羽状图的绘制模板&#xff1a; 进一步&#xff0c;再来分享一下箭头图的绘制模板。 先来看一下成品效果&#xff1a; 特别提示&#xff1a;本期内容『数据代码』已上传资源群中&#xff0c;加群的朋友请自行下载。有需要的朋友可以关注…

今天,我终于学懂了C++中的引用

文章目录一、前言二、概念介绍三、引用的五大特性1、引用在定义时必须初始化2、一个变量可以有多个引用3、一个引用可以继续有引用4、引用一旦引用一个实体&#xff0c;再不能引用其他实体5、可以对任何类型做引用【变量、指针....】四、引用的两种使用场景1、做参数a.案例一&a…

JavaScript前端面试题

资料总结/刷题指南 简答题 1、什么是防抖和节流&#xff1f;有什么区别&#xff1f;如何实现&#xff1f; 参考答案 防抖 触发高频事件后 n 秒内函数只会执行一次&#xff0c;如果 n 秒内高频事件再次被触发&#xff0c;则重新计算时间 思路&#xff1a; 每次触发事件时都取…

Python的知识点运用-1(日期转换)

问&#xff1a;如何将 星期一, 三月 13, 2023转换成2023-03-13看到这个问题&#xff0c;你的第一反应是什么&#xff1f;&#xff1f;&#xff1f;反正我是懵逼的。不过后面一想&#xff0c;时间模块可以。在这个问题后面&#xff0c;群友又问了一个问题&#xff0c;如何在本地…

h0043. 奇怪的汉诺塔

汉诺塔问题&#xff0c;条件如下&#xff1a; 1、这里有A、B、C和D四座塔。 2、这里有n个圆盘&#xff0c;n的数量是恒定的。 3、每个圆盘的尺寸都不相同。 4、所有的圆盘在开始时都堆叠在塔A上&#xff0c;且圆盘尺寸从塔顶到塔底逐渐增大。 5、我们需要将所有的圆盘都从…