hutool poi、apache poi实现导入导出以及解析excel

这篇具有很好参考价值的文章主要介绍了hutool poi、apache poi实现导入导出以及解析excel。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

一、前言

看了例子之后后续需要更加深入学习或者更多理解其他API的话,建议看官方文档。hutool项目是中国人维护的,有中文文档,阅读起来很方便。apache poi比较底层一点,可以更加自由去二次开发自己所需的功能。

hutool官方文档
hutool官方gitee
apache poi官方文档

二、基于hutool poi 实现导出excel文件到本地

有两种写法,可以一开始就为ExcelWriter 指定要写的文件,另一种是等到要flush的时候再指定对应文件的输出流。两种写法都能实现,不过第二种写法会显得更灵活一点,可以到后面再慢慢决定要输出到哪个文件。

具体实现逻辑
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class PoiTest {
    private int age;
    private String name;

   
    public PoiTest() {
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public PoiTest(int age, String name) {
        this.age = age;
        this.name = name;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        PoiTest poiTest = (PoiTest) o;
        return age == poiTest.age && Objects.equals(name, poiTest.name);
    }

    @Override
    public int hashCode() {
        return Objects.hash(age, name);
    }

    @Override
    public String toString() {
        return "PoiTest{" +
                "age=" + age +
                ", name='" + name + '\'' +
                '}';
    }

    public static void main(String[] args) throws IOException {
    	//方式一
        File file=new File("E:\\自测资料\\test.xlsx");
        file.createNewFile();
        ExcelWriter bigWriter = ExcelUtil.getBigWriter();
        bigWriter.setDestFile(file);
        List<PoiTest> list=new ArrayList<>();
        for (int i=0;i<10;i++){
            list.add(new PoiTest(18+i,"小明"+i));
        }
        //将数据写入到ExcelWriter的workbook中
        bigWriter.write(list);
        //将数据写入excel表
        bigWriter.flush();
        //关闭资源
        bigWriter.close();
		
//		//方式二
//        ExcelWriter bigWriter = ExcelUtil.getBigWriter();
//        List<PoiTest> list=new ArrayList<>();
//        for (int i=0;i<10;i++){
//            list.add(new PoiTest(18+i,"小明"+i));
//        }
//        bigWriter.write(list);
//
//        File file=new File("E:\\自测资料\\test.xlsx");
//        file.createNewFile();
//        OutputStream outputStream=new FileOutputStream(file);
//        bigWriter.flush(outputStream);
//        bigWriter.close();
    }
}

运行结果

hutool poi、apache poi实现导入导出以及解析excel

三、基于hutool poi 实现从本地导入excel文件并转成对象列表

导入可以用map,list,对象来存储一行记录,推荐使用对象,方便后期使用。

具体实现逻辑
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
public class PoiTest {
    private int age;
    private String name;

   
    public PoiTest() {
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public PoiTest(int age, String name) {
        this.age = age;
        this.name = name;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        PoiTest poiTest = (PoiTest) o;
        return age == poiTest.age && Objects.equals(name, poiTest.name);
    }

    @Override
    public int hashCode() {
        return Objects.hash(age, name);
    }

    @Override
    public String toString() {
        return "PoiTest{" +
                "age=" + age +
                ", name='" + name + '\'' +
                '}';
    }

    public static void main(String[] args) throws IOException {
//方式一
        File file=new File("E:\\自测资料\\test.xlsx");
        ExcelReader reader = ExcelUtil.getReader(file);
        //list中的每个map对应excel表中的一行记录,excel表第一行(字段名)当作key,value就是行记录对应列的值
        List<Map<String, Object>> maps = reader.readAll();
        for(Map map:maps){
            Set<String> set = map.keySet();
            for(String key:set){
                System.out.println(key+"-->"+map.get(key));
            }
            System.out.println("-----------");
        }
        reader.close();
	
//方式二	
//        //list返回,内部的list,每一个list代表一行记录,第一行记录可以当作表头。
//        List<List<Object>> read = reader.read();
//        for(List list:read){
//            for (Object o:list){
//                System.out.println(o);
//            }
//            System.out.println("-----");
//        }
//        reader.close();

//方式三
//        //根据表头名和实体对象字段名来匹配记录,并返回实体列表
//        File file=new File("E:\\自测资料\\test.xlsx");
//        ExcelReader reader = ExcelUtil.getReader(file);
//        /**
//         *  第一个参数是表头所在行;第二个参数是读取数据开始行,会自动过滤掉表头行;第三个参数是实体类
//         *  如果行记录所有列都为空,则会跳过该行记录,不创建对象。只要有一个列是不为空的,就会创建对象
//         **/
//        List<PoiTest> read = reader.read(0, 0, PoiTest.class);
//        reader.close();
//        for(PoiTest poiTest:read){
//            System.out.println(poiTest);
//        }
    }
}

运行结果

map方式返回结果

hutool poi、apache poi实现导入导出以及解析excel
list方式返回结果:(excel中只要行记录存在,那么空的列会保存为空字符串)
hutool poi、apache poi实现导入导出以及解析excel
对象列表方式返回结果:
hutool poi、apache poi实现导入导出以及解析excel

四、基于apache poi实现根据传入的类将excel的输入流解析成类对象(excel解析原理)

这个就是我们日常使用的excel上传功能,因此非常有必要掌握原理。
一开始就想过可以通过传入类名,结合反射机制来创建对象,还可以获取对象的字段并赋值,实际上思路也确实大概这样。我从chat-gpt拿到了一个解析excel输入流的demo,不过这个demo并没有把excel表第一行当作表头;因此,我在这个基础上做了一些修改,实现了解析excel文件输入流成对象的工具类方法。(tips:支持的数据类型只能是比较基础的类型,不能是复杂的对象,复杂对象先json字符串接收,后面再自己转)
动态代理太酷啦!!!

当然,根据hutool的工具类就有现成的方法。
ExcelReader reader=getReader(InputStream bookStream)
调用reader的各种方法就可以实现解析成各种形式的对象了。

实体类对象(也就是要解析成的对象)
package com.yumoxuan.pojo;
import java.util.Date;
import java.util.Objects;
public class Person {
    private int age;
    private String name;
    private Date birthday;
    private double high;

    public Person() {
    }

    public Date getBirthday() {
        return birthday;
    }

    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }

    public double getHigh() {
        return high;
    }

    public void setHigh(double high) {
        this.high = high;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Person person = (Person) o;
        return age == person.age &&
                Double.compare(person.high, high) == 0 &&
                Objects.equals(name, person.name) &&
                Objects.equals(birthday, person.birthday);
    }

    @Override
    public int hashCode() {
        return Objects.hash(age, name, birthday, high);
    }

    @Override
    public String toString() {
        return "Person{" +
                "age=" + age +
                ", name='" + name + '\'' +
                ", birthday=" + birthday +
                ", high=" + high +
                '}';
    }
}
具体实现逻辑
import com.yumoxuan.pojo.Person;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.*;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.lang.reflect.Field;
public class ExcelParser {
    public static <T> List<T> parseExcelFile(InputStream inputStream, Class<T> clazz) {
        List<T> objectList = new ArrayList<>();

        try (Workbook workbook = new XSSFWorkbook(inputStream)) {
            Sheet sheet = workbook.getSheetAt(0); // Assuming the data is in the first sheet

            // Get the field names from the class
            Field[] fields = clazz.getDeclaredFields();
             List<String> objectFieldNameList= Arrays.stream(fields).map(o->o.getName()).collect(Collectors.toList());
            //获取excel第一行作为对象的字段名
                       List<String> excelFieldNameList = new ArrayList<>();
            boolean firstRow = true;
            // Iterate over rows in the sheet
            for (Row row : sheet) {
                T object = clazz.newInstance(); // Create an instance of the class

                // Map cell values to object fields
                int i = 0;
                for (Cell cell : row) {
                    if (firstRow) {
                        //获取excel表的第一行作为字段名
                        excelFieldNameList.add(cell.getStringCellValue());
                        continue;
                    }
                   	
                    if(!objectFieldNameList.contains(excelFieldNameList.get(i))){
                        //过滤excel中存在,但类中不存在的字段
                        continue;
                    }
                    //注意,这里如果尝试获取类里面没有的字段,会抛异常,因此excel表结构最好协商定下来。当然有了上一步的判断,这个问题不会发生
                    Field field = clazz.getDeclaredField(excelFieldNameList.get(i));
                    //开启编辑权限
                    field.setAccessible(true);
                    Class<?> fieldType = field.getType();

                    // 这里只需要把可能的数据类型都加上就可以了;不过一般也就那么基本数据类型加上字符串
                    if (fieldType == String.class) {
                        field.set(object, cell.getStringCellValue());
                    } else if (fieldType == int.class || fieldType == Integer.class) {
                        field.set(object, (int) cell.getNumericCellValue());
                    } else if (fieldType == boolean.class || fieldType == Boolean.class) {
                        field.set(object, cell.getBooleanCellValue());
                    } else if (fieldType == double.class || fieldType == Double.class) {
                        field.set(object, cell.getNumericCellValue());
                    } else if (fieldType == float.class || fieldType == Float.class) {
                        field.set(object, (float) cell.getNumericCellValue());
                    } else if (fieldType == Date.class) {
                        field.set(object, cell.getDateCellValue());
                    } else {
                        //暂不支持的类型
                    }
                    i++;
                    //关闭编辑权限
                    field.setAccessible(false);
                }
                if (!firstRow) {
                    objectList.add(object);
                }
                firstRow = false;
            }
        } catch (IOException | ReflectiveOperationException e) {
            e.printStackTrace();
        }

        return objectList;
    }

    public static void main(String[] args) throws FileNotFoundException {
        File file = new File("F:\\JAVA\\test.xlsx");
        InputStream inputStream = new FileInputStream(file);
        List<Person> people = ExcelParser.parseExcelFile(inputStream, Person.class);
        for (Person person : people) {
            System.out.println(person);
        }
    }
}

excel文件路径及数据

hutool poi、apache poi实现导入导出以及解析excel

运行结果

Person{age=18, name=‘张三’, birthday=Mon Dec 25 12:13:00 CST 2000, high=163.25}
Person{age=19, name=‘李四’, birthday=Tue Dec 26 12:13:00 CST 2000, high=180.25}

学无止境,共勉。如果有帮到你,给我点个赞吧。文章来源地址https://www.toymoban.com/news/detail-485967.html

到了这里,关于hutool poi、apache poi实现导入导出以及解析excel的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包赞助服务器费用

相关文章

  • Apache POI 以及 导出Excel表

    Apache POI 是一个处理Miscrosoft Office各种文件格式的开源项目。简单来说就是,我们可以使用 POI 在 Java 程序中对Miscrosoft Office各种文件进行读写操作。 一般情况下,POI 都是用于操作 Excel 文件。 导依赖 将数据写入Excel文件 读取Excel文件数据 学习

    2024年02月11日
    浏览(16)
  • 数据导入导出(POI以及easyExcel)

    数据导入导出(POI以及easyExcel)

            将一些数据库信息导出为Excel表格         将Excel表格数据导入数据库         大量数据的导入导出操作 常⽤的解决⽅案为: Apache POI 与阿⾥巴巴 easyExcel Apache POI 是基于 Office Open XML 标准( OOXML )和 Microsoft 的 OLE 2 复合⽂档 格式( OLE2 )处理各种⽂件格式的

    2024年02月13日
    浏览(13)
  • POI 实现Excel导入导出

    什么是POI Apache POI 是用Java编写的免费开源的跨平台的 Java API,Apache POI提供API给Java程序对Microsoft Office格式档案读和写的功能。POI为“Poor Obfuscation Implementation”的首字母缩写,意为“简洁版的模糊实现”。 生成xls和xlsx有什么区别呢? XLS XLSX 只能打开xls格式,无法直接打开x

    2024年02月03日
    浏览(15)
  • poi技术实现数据的导入与导出

    poi技术实现数据的导入与导出

    前言: POI是Apache软件基金会的开放源码函式库,POI提供API给Java程序对Microsoft Office格式档案读和写的功能。 Microsoft Office:是由微软公司开发的一套 办公软件套装 。常用组件有Word、Excel、PowerPoint等。 POI也用于操作Excel(电子表格) 一个excel文件就是一个工作簿Workbook 一个工

    2024年02月05日
    浏览(12)
  • poi实现Excel文件的导入导出

    poi结构说明 引入poi依赖包 第一步、获取表内容数据: 根据表头内容与实体类属性对应的map,利用反射机制获取get方法来取出该实体数据 第二步、开始导出 编辑表格内样式 第三步、设定响应请求头格式,发送文件到客户端 判断表格行数据是否为空 判断表格列值是否为空 设

    2024年02月12日
    浏览(16)
  • Java原生POI实现的Excel导入导出(简单易懂)

    Java原生POI实现的Excel导入导出(简单易懂)

    首先是Controller入口方法 这个接口在postman上传参是下面这样的: 注意里面的参数名称要和接口上的一致,不然会拿不到值 还有file那里key的类型要选file类型的,这样就可以在后面value里面选择文件 然后是Service方法 首先是Controller入口 strJson是用来接受其它参数的,一般导出的

    2024年02月11日
    浏览(14)
  • 使用POI和EasyExcel来实现excel文件的导入导出

    使用POI和EasyExcel来实现excel文件的导入导出

    废话不多说咱们直接上干货!!!! 一.读取Excel表格 【1】使用POI读取excel表格中的数据 POI还可以操作我们这个word文档等等,他不仅仅只能弄Excel,而JXI只能操作excel 1.POI的结构,我们可以更具文件的类去选择 相关的对象我当前是使用的XLSX来操作的 HSSF - 提供读写Microsoft

    2024年02月05日
    浏览(11)
  • poi实现excel文件导入导出(基本数据导出、含格式导出、含批注导出、含图片图表导出)——springboot

    poi实现excel文件导入导出(基本数据导出、含格式导出、含批注导出、含图片图表导出)——springboot

    本文主要是介绍springboot + poi实现基本的excel文件导入导出,包含数据导出导入时数据的其他需求校验,导出含有批注信息、导出含有图片信息、导出含有图表信息等的介绍等等,主要是一个demo尽可能简单明了的来介绍相关功能即可。有什么问题可以在留言哦!并在文章末尾附

    2024年02月08日
    浏览(20)
  • Apache POI 导出Excel报表

    Apache POI 导出Excel报表

    大家好我是苏麟 , 今天聊聊Apache POI . 介绍 Apache POI 是一个处理Miscrosoft Office各种文件格式的开源项目。简单来说就是,我们可以使用 POI 在 Java 程序中对Miscrosoft Office各种文件进行读写操作。 一般情况下,POI 都是用于操作 Excel 文件。 官网 : Apache POI - the Java API for Microsoft Do

    2024年01月17日
    浏览(13)
  • 12、POI之数据导入导出

    12、POI之数据导入导出

    【简介】: POI简介(Apache POI),Apache POI是Apache软件基金会的开放源码函式库,POI提供API给Java程序对Microsoft Office格式档案读和写的功能。 【官网】: Apacche POI 官网 【主要包含模块】: HSSF - 提供读写Microsoft Excel格式档案的功能。(.xls) XSSF - 提供读写Microsoft Excel OOXML格

    2024年02月07日
    浏览(13)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包