การอ่าน excel ด้วย JExcelApi
หลังจากบทความที่แล้ว เราได้ทำการเขียน excel ด้วย JExcelApi แล้วบทรวามนี้เราก็มาต่อยอดกันด้วยการอ่าน
excel กันหล่ะกันนะครับเพื่อมไ่เป็นการเสียเวลาเราเริ่มกันเลยหล่ะกัน
String filename = "test.xls"; // กำหนดชื่อไฟล์ของ excel
WorkbookSettings ws = new WorkbookSettings();
ws.setLocale(new Locale("en", "EN"));
Workbook workbook = Workbook.getWorkbook(new File(filename),ws);
Sheet s = workbook.getSheet(0); //กำหนด sheet ที่ต้องการจะอ่านข้อมูล
Cell cell = s.getCell(1, 1); // อ่านข้อมูล ณ. ตำแหน่ง (x,y)
System.out.println(cell.getContents());
อีกตัวอย่าง
excel กันหล่ะกันนะครับเพื่อมไ่เป็นการเสียเวลาเราเริ่มกันเลยหล่ะกัน
String filename = "test.xls"; // กำหนดชื่อไฟล์ของ excel
WorkbookSettings ws = new WorkbookSettings();
ws.setLocale(new Locale("en", "EN"));
Workbook workbook = Workbook.getWorkbook(new File(filename),ws);
Sheet s = workbook.getSheet(0); //กำหนด sheet ที่ต้องการจะอ่านข้อมูล
Cell cell = s.getCell(1, 1); // อ่านข้อมูล ณ. ตำแหน่ง (x,y)
System.out.println(cell.getContents());
อีกตัวอย่าง
String strc00 = null;
double strc10 = 0.00;
Date strc11 = null;
Cell c00 = rs.getCell(0, 0);
Cell c10 = rs.getCell(1, 0);
Cell c11 = rs.getCell(1, 1);
if(c00.getType() == CellType.LABEL) // ตรวจสอบว่า cell ที่เราอ่านนั้นเป็นชนิดข้อความหรือไม่
{
LabelCell labelc00 = (LabelCell)c00;
strc00 = labelc00.getString();
}
if(c10.getType() == CellType.NUMBER)// ตรวจสอบว่า cell ที่เราอ่านนั้นเป็นชนิดตัวเลขหรือไม่
{
NmberCell numc10 = (NumberCell)c10;
strc10 = numc10.getValue();
}
if(c11.getType() == CellType.DATE) // ตรวจสอบว่า cell ที่เราอ่านนั้นเป็นชนิด DATE หรือไม่
{
DateCell datec11 = (DateCell)c11;
strc11 = datec11.getDate();
}
System.out.println("Cell(0, 0)" + " value : " + strc00 + "; type : " + c00.getType());
System.out.println("Cell(1, 0)" + " value : " + strc10 + "; type : " + c10.getType());
System.out.println("Cell(1, 1)" + " value : " + strc11 + "; type : " + c11.getType());
เมื่อทำการเลิกใช้งาน sheet แล้วให้ทำการปิด workbook ด้วย method close
workbook.close();
Comments