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

查看:274
本文介绍了如何使用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 anand
  • 02库马尔

和我的Java对象

Employee{
String empNo;
String empName; 
}

现在,我要将Excel工作表转换为Java对象. 我曾在Internet上尝试过,但是大多数教程都讨论了迭代每一行并为对象的每个成员分配值. 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天全站免登陆