如何使用 Apache POI 将我的 xlsx 表转换为 java 对象 [英] How to convert my xlsx sheet to java object using Apache POI

查看:30
本文介绍了如何使用 Apache POI 将我的 xlsx 表转换为 java 对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

任何人都可以建议我使用 Apache POI 将我的 xlsx 表转换为 java 对象.

can any one suggest me to convert my xlsx sheet to java object using Apache POI.

eq,我的excel表包含两列

eq, my excel sheet contains two columns

  • emp_no emp_name
  • 01 和
  • 02 库马尔

和我的java对象

Employee{
String empNo;
String empName; 
}

现在我想将我的 excel 表转换为 java 对象.我曾在互联网上尝试过,但大多数教程都讨论了迭代每一行并为对象中的每个成员分配值.JAXB xml 解析器中是否有任何像 Marshaller 和 UnMarshaller 这样的功能可以直接转换.

Now I want to convert my excel sheet to java object. I have tried in internet but most of the tutorials talks about iterate each row and assign values to each member sin the object. Is there any functionality like Marshaller and UnMarshaller in JAXB xml parser which convert directly.

提前致谢.

推荐答案

对于给定的场景,我假设工作表的每一行都代表一个员工,其中第一列是员工编号,第二列是员工姓名.所以你可以使用以下内容:

For the given Scenario, I am assuming that each row of the sheet is representing an employee of which say first Column is keeping employee Number and second column is keeping Employee Name. so you can use the following:

Employee{
  String empNo;
  String empName; 
}

创建一个分配Employee信息的方法

Create a method of assigning the Employee information as

assignEmployee(Row row){
    empNo = row.getCell(0).toString();
    empName = row.getCell(1).toString();
}

或者如果你愿意,你可以为它创建一个构造函数.

or if you want you can create a constructor for the same.

现在您只需要遍历每一行即可使用上述方法获取/使用信息.

Now you just need to iterate over each row to get/use the information using the above method.

Employee emp = new Employee();
Iterator<Row> itr = sheet.iterator();
    while(itr.hasNext()){
       Row row = itr.next();
       emp.assignEmployee(row);
      //  enter code here for the rest operation
}

这篇关于如何使用 Apache POI 将我的 xlsx 表转换为 java 对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆