需要下載 jxl-2.6.10.jar
public class ImportExcelUnits {
public static List<Object[]> readExcel(File file, int beginIndex) throws Exception{ // beginIndex 重第幾行開始解析
List<Object[]> result = null;
Object[] tempData = null;
try {
if(file != null){
Workbook workbook = Workbook.getWorkbook(file);
Sheet sheet = workbook.getSheet(0);
Cell cell = null;
int rowSize = sheet.getRows();
int colSize = sheet.getColumns();
result = new ArrayList<Object[]>();
for (int i = beginIndex - 1; i < rowSize; i++) {
tempData = new Object[colSize];
for (int t = 0; t < colSize; t++) {
// 保存EXCEL每行的所有單元格中的數據,在內循環外面進行定義
cell = sheet.getCell(t, i);
String content = "";
if (cell.getContents() != null && !"".equals(cell.getContents().trim())) {
// 去空格,特殊字符和回車鍵盤
content = cell.getContents().replace("%", "")
.replace("|", "").replace(" ", "")
.replaceAll("\\n", "")
.replaceAll("\\r", "").trim();
tempData[t] = content;
}
}
// 將每列的數據存入結果集中
result.add(tempData);
}
}
} catch (Exception e) {
throw new Exception("解析Excel表格出錯..\n" + e.getMessage());
}
return result;
}
//測試
public static void main(String[] args) throws Exception {
File file=new File("C:\\Documents and Settings\\Administrator\\桌面\\食品安全\\食品安全數據\\望京西園\\2013朝陽管字2738164.csv");
List<Object[]> list = ImportExcelUnits.readExcel(file, 3);
System.out.println(list);
}
}