java讀取excel檔案內容
阿新 • • 發佈:2018-11-28
import java.io.FileInputStream;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.CellType;
public class POIReadExcelTool { public static void main(String[] args) throws Exception { List<Student> list = readXls(); for(Student stu : list){ System.out.println(stu.getId()); System.out.println(stu.getName()); System.out.println(stu.getAge()); System.out.println(stu.getBirth()); } } public static List<Student> readXls() throws Exception { InputStream is = new FileInputStream("D:/info.xls"); HSSFWorkbook excel = new HSSFWorkbook(is); Student stu = null; List<Student> list = new ArrayList<Student>(); // 迴圈工作表Sheet for (int numSheet = 0; numSheet < excel.getNumberOfSheets(); numSheet++) { HSSFSheet sheet = excel.getSheetAt(numSheet); if (sheet == null) continue; // 迴圈行Row for (int rowNum = 1; rowNum < sheet.getLastRowNum(); rowNum++) { HSSFRow row = sheet.getRow(rowNum); if (row == null) continue; stu = new Student(); HSSFCell cell0 = row.getCell(0); if (cell0 == null) continue; stu.setId((int)cell0.getNumericCellValue()); HSSFCell cell1 = row.getCell(1); if (cell1 == null) continue; stu.setName(cell1.getStringCellValue()); HSSFCell cell2 = row.getCell(2); if (cell2 == null) continue; stu.setAge((int)cell2.getNumericCellValue()); HSSFCell cell3 = row.getCell(3); if (cell3 == null) continue; // stu.setBirth(new SimpleDateFormat("yyyy-mm-dd").parse(cell3.getStringCellValue())); list.add(stu); } } return list; } @SuppressWarnings("unused") private static String getValue(HSSFCell cell) { if (cell.getCellType() == CellType.BOOLEAN) { // 返回布林型別 值 return String.valueOf(cell.getBooleanCellValue()); } else if (cell.getCellType() == CellType.NUMERIC) { //返回數值型別的值 return String.valueOf(cell.getNumericCellValue()); } else { //返回字串型別的值 return cell.getStringCellValue(); } } }
import java.util.Date;
public class Student {
private int Id;
private String Name;
private int age;
private Date Birth;
public int getId() {
return Id;
}
public void setId(int id) {
Id = id;
}
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public Date getBirth() {
return Birth;
}
public void setBirth(Date birth) {
Birth = birth;
}
}