Redian新闻
>
Java导入、导出excel保姆级教程(附封装好的工具类)

Java导入、导出excel保姆级教程(附封装好的工具类)

公众号新闻

👉 这是一个或许对你有用的社群

🐱 一对一交流/面试小册/简历优化/求职解惑,欢迎加入芋道快速开发平台知识星球。下面是星球提供的部分资料: 

👉这是一个或许对你有用的开源项目

国产 Star 破 10w+ 的开源项目,前端包括管理后台 + 微信小程序,后端支持单体和微服务架构。

功能涵盖 RBAC 权限、SaaS 多租户、数据权限、商城、支付、工作流、大屏报表、微信公众号等等功能:

  • Boot 地址:https://gitee.com/zhijiantianya/ruoyi-vue-pro
  • Cloud 地址:https://gitee.com/zhijiantianya/yudao-cloud
  • 视频教程:https://doc.iocoder.cn

来源:blog.csdn.net/qq_42785250
/article/details/129654178


前言

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

基于 Spring Boot + MyBatis Plus + Vue & Element 实现的后台管理系统 + 用户小程序,支持 RBAC 动态权限、多租户、数据权限、工作流、三方登录、支付、短信、商城等功能

  • 项目地址:https://github.com/YunaiV/ruoyi-vue-pro
  • 视频教程:https://doc.iocoder.cn/video/

一、引入Apache POI依赖

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

 <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>

基于 Spring Cloud Alibaba + Gateway + Nacos + RocketMQ + Vue & Element 实现的后台管理系统 + 用户小程序,支持 RBAC 动态权限、多租户、数据权限、工作流、三方登录、支付、短信、商城等功能

  • 项目地址:https://github.com/YunaiV/yudao-cloud
  • 视频教程:https://doc.iocoder.cn/video/

二、用法&步骤

2.1 创建Excel的元素

1)创建WokrBook

Workbook workbook = new XSSFWorkbook();

2)创建Sheet

 Sheet sheet = workbook.createSheet();

设置sheet的名称

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

3)创建行Row

Row row = sheet.createRow(0);

4)创建单元格Cell

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

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

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

5) 填充数据

 cell.setCellValue("苹果");

2.2 样式和字体

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

创建样式:

CellStyle cellStyle = workbook.createCellStyle();

1)左右垂直居中

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

2)字体加粗、颜色

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

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

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

cell.setCellStyle(style);

3)调整列宽和高

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

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

4)倾斜、下划线

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

2.3 进阶用法

1)合并单元格

Workbook workbook = new XSSFWorkbook();
Sheet sheet = workbook.createSheet(fileName);
sheet.addMergedRegion(new CellRangeAddress(0005));

CellRangeAddress()方法四个参数分别是fristRow:起始行、lastRow:结束行、fristCol:起始列、lastCol:结束列。

如果你想合并从第一行到第二行从一列到第十列的单元格(一共合并20格),那么就是CellRangeAddress(0,1,0,10)

2)字段必填

//创建数据验证
DataValidationHelper dvHelper = sheet.getDataValidationHelper();
//创建要添加校验的单元格对象
CellRangeAddressList addressList = new CellRangeAddressList(00010);
//创建必填校验规则
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:求和函数

//创建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:平均数函数

//创建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:计数函数

//创建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:条件函数

//创建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:连接函数

//创建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)下拉选择

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

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

数字格式

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

日期格式

// 设置单元格样式 - 日期格式
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层代码:

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)代码

@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.classresponse);
}

2)工具类

  /**
 * 数据导出
 * @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);
    }
}

3)结果

四、导入完整示例

1)代码

@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)工具类

 /**
     * 导入
     * @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)结果

学生信息集合:


欢迎加入我的知识星球,全面提升技术能力。

👉 加入方式,长按”或“扫描”下方二维码噢

星球的内容包括:项目实战、面试招聘、源码解析、学习路线。

文章有帮助的话,在看,转发吧。

谢谢支持哟 (*^__^*)

微信扫码关注该文公众号作者

戳这里提交新闻线索和高质量文章给我们。
相关阅读
从“大陆不惜死亡一亿四千万年轻人”谈起b?b?h?h风中有朵雨做的云4个高手专用的Excel小技巧,让你的工作效率翻倍!SpringBoot 中的自带工具类,开发效率倍增!肝了两小时的 Elasticsearch 保姆级入门外网好评度爆了!适合商科生的Tableau可视化教程(附内部资源)VLOOKUP靠边站,这才是Excel中最牛的查找方法?(建议收藏)通宵整理的100份Excel表格模板,免费送!我熬夜整理了近1000篇Excel教程合集,免费分享!哭了!影响因子暴跌!某院校医学博士上网求助,结果……(附IF汇总Excel)有了ModelScope-Agent,小白也能打造专属智能体,附保姆级教程Java 导出 Excel 利器:JXLS突发!摩根大通掀起Python转型,金融圈再无Excel?高盛官方出品投行Excel教程,留学生狂喜:2天搞定,比学校教得有用保姆级教程:Spring Cloud 集成 Seata 分布式事务再见,VLOOKUP!全行业必备的Excel实操大全,请低调使用!Vue+SpringBoot 集成 PageOffice 实现在线编辑Word、excel文档J.P.Morgan官宣:这张Excel证书,留学生无门槛直接拿!Common App开放!吹响2024申请号角,附保姆级填写教程!ChatGPT神器Code Interpreter终于开放,到底怎么用?这里有一份保姆级教程看完高盛Banker晒出的Excel证书,才懂人和人的差距!用PQ太难,手动太慢,这才是最牛x的Excel统计工具!J.P.Morgan认证的Excel证书,我自学2周线上搞定!Jenkins 真得很牛逼!只是大部分人不会用而已~(保姆级教程)Excel最新版官方支持Python,打工人的工具又强化了J.P.Morgan认可的Excel证书,我自学2天搞定高盛出品投行Excel教程,留学生狂喜:2天搞定,比学校教得有用SpringBoot 集成 EasyExcel 3.x 优雅实现 Excel 导入导出“精华”导入,导入的是什么?玩转 ReflectionUtils 工具类,离大佬又近一步《僭越之殇》(15)——守护天使边读木心《文学回忆录》边记高盛、大小摩内部疯传的Excel教程,一个字:绝!品牌从0到1小红书种草打法,保姆级教程来了
logo
联系我们隐私协议©2024 redian.news
Redian新闻
Redian.news刊载任何文章,不代表同意其说法或描述,仅为提供更多信息,也不构成任何建议。文章信息的合法性及真实性由其作者负责,与Redian.news及其运营公司无关。欢迎投稿,如发现稿件侵权,或作者不愿在本网发表文章,请版权拥有者通知本网处理。