[英]Create object from Excel using Apache Poi
我正在嘗試從Excel創建對象。 Excel文件看起來像這樣
我試圖從這篇文章中遵循這個想法如何使用Apache POI將我的xlsx工作表轉換為java對象 。 第一個答案看起來不錯。 但是,我對如何創建對象的了解很少。
public class Tr {
String empName;
String empID;
String empDept;
//Constructor
public Tr(String empName, String empID, String empDept) {
this.empName = empName;
this.empID = empID;
this.empDept = empDept;
}
//The following part will read Excel and return cell data
public static ArrayList<String> name = new ArrayList<String>();
public static ArrayList<String> deptId = new ArrayList<String>();
public static ArrayList<String> dName = new ArrayList<String>();
public ArrayList<String> getCellData(int cellNo) throws IOException {
FileInputStream file = new FileInputStream("C:\\MyTemp\\People.xlsx");
HSSFWorkbook book = new HSSFWorkbook(file);
HSSFSheet sheet = book.getSheet("Sheet1");
Iterator<Row> it = sheet.iterator();
ArrayList<String> cellData = new ArrayList<String>();
while (it.hasNext()) {
cellData.add(it.next().getCell(cellNo).getStringCellValue());
}
return cellData;
}
//Assigning cell data to variables and converting to string
public void assignEmployee() throws IOException {
empName = getCellData(0).toString();
empID = getCellData(1).toString();
empDept = getCellData(2).toString();
}
public static void main(String[] args) {
}
}
您的幫助或想法將不勝感激。 謝謝。
您鏈接到的答案並不完全是這種方式。 該答案建議您應該一次加載excel文件,然后迭代每個Row
以便將其分配給Employee
實例。
因此基本用法如下:
FileInputStream file = new FileInputStream("C:\\MyTemp\\People.xlsx");
HSSFWorkbook book = new HSSFWorkbook(file);
HSSFSheet sheet = book.getSheet("Sheet1");
Iterator<Row> it = sheet.iterator();
Employee emp = new Employee();
while(itr.hasNext()){
Row row = itr.next();
emp.assignEmployee(row);
// use emp instance here
}
換句話說, Employee
類將如下所示:
public class Employee{
private String empNo;
private String empName;
public void assignEmployee(Row row) {
empNo = row.getCell(0).toString();
empName = row.getCell(1).toString();
}
}
在這里,您可以將Employee
實例用於所需的任何范圍。 我個人將更進一步,並在Employee
的構造函數中進行賦值,而不要使用一個名為assignEmployee
的方法(這樣可能會導致線程問題)。
Iterator<Row> it = sheet.iterator();
while(itr.hasNext()){
Row row = itr.next();
Employee emp = new Employee(row);
// use emp instance here
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.