這段時間,由於工作原因,需要處理好幾千條資料,於是從庫把資料倒出來,產生的是excel檔案。
對於大量重複的操作,人工一個個來處理費時費勁易錯,所以就想了搞個程式來處理這些excel裡的
資料,於是寫了個程式,可以解析excel2007的文檔。註:之前用的版本低,報不能錯裡excel2007
的錯誤,後面改成poi-3.8就可以支援2007了。如果大家碰到類似的問題,可以升級下版本就ok了。
還有一些經驗就是,單excel某列的數值資料查詢出來為科學計數法形式,可以根據需要,如Integer類型,
可以講查出的值扔進Integer的建構函式中,從而實現將科學計數值轉為普通的數值,如果某類為空白(不是null),
即某列沒有數值,poi讀取時不會報錯,但是讀會卡在這裡了,一個解決方案就是給這列賦一個null的值,這樣
poi就可以繼續讀取整個excel的資料了。
以下是我寫的一個簡單的例子,希望對初次使用的朋友有借鑒之用:
package test;
import java.io.IOException;
import java.util.Date;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
/**
* 操作Excel表格的功能類
*
* @author:hnhychl
* @version 1.0
*/
public class ExcelReader {
private static XSSFWorkbook xwb;
private static XSSFSheet sheet;
private static XSSFRow row;
public static void readExcle2007() {
try {
xwb = new XSSFWorkbook("c:\\lpk.xlsx");
sheet = xwb.getSheetAt(0);
String cell;
// System.out.println("physical rows = "+ sheet.getPhysicalNumberOfRows());
// System.out.println("physical cols = "+ sheet.getRow(1).getPhysicalNumberOfCells());
// 列表從0開始
// System.out.println("first cols ="+sheet.getRow(1).getFirstCellNum());
for (int i = sheet.getFirstRowNum() + 1; i < sheet.getLastRowNum(); i++) {
row = sheet.getRow(i);
System.out.println("row = " + row.getRowNum());
/**
* 讀取所有資料
*/
// for (int j = row.getFirstCellNum(); j < row.getPhysicalNumberOfCells(); j++) {
// row.getCell(j, Row.RETURN_NULL_AND_BLANK).setCellType(Cell.CELL_TYPE_STRING);
// cell = row.getCell(j).getStringCellValue();
// System.out.print(cell+"\t");
// }
Date beginDate = row.getCell(2).getDateCellValue();
Date endDate = row.getCell(3).getDateCellValue();
Date activityDate = row.getCell(4).getDateCellValue();
// 判斷禮品卡是否有超額的或到期的情況,如果超額或者到期,這輸出有問題的訂單號
if (row.getCell(6).getNumericCellValue() > row.getCell(7).getNumericCellValue() || beginDate.after(endDate) || null == activityDate)
System.out.println(row.getCell(0).getStringCellValue());
}
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
//檢測代碼
try {
// 讀取excel2007
readExcle2007();
} catch (Exception ex) {
}
Long endTime = System.currentTimeMillis();
}
}
以上程式依賴外掛程式poi-3.8,大家可以從我的資源裡無償下載,代碼拷過來就可以跑了。添加支援有: