我正在製作一個程序,用於從excel文件中讀取數據並將它們存儲在表格中。我使用Apache POI編寫了程序並且工作正常。但是當文件空白單元格爲時,我遇到了一些問題。程序跳過空白並讀取下一個數據。任何人都可以幫助我如何做到這一點?我知道這個問題有幾個帖子,但我沒有找到對我有用的東西。如何處理excel文件中的空白單元格java
從excel文件中讀取數據的代碼如下。正如你所看到的,我有3種類型的數據。我會如何爲BLANK CELL提供選項?
// Create an ArrayList to store the data read from excel sheet.
List sheetData = new ArrayList();
FileInputStream fis = null;
try {
// Create a FileInputStream that will be use to read the
// excel file.
fis = new FileInputStream(strfullPath);
// Create an excel workbook from the file system
HSSFWorkbook workbook = new HSSFWorkbook(fis);
// Get the first sheet on the workbook.
HSSFSheet sheet = workbook.getSheetAt(0);
// store the data read on an ArrayList so that we can printed the
// content of the excel to the console.
Iterator rows = sheet.rowIterator();
while (rows.hasNext()) {
HSSFRow row = (HSSFRow) rows.next();
Iterator cells = row.cellIterator();
List data = new ArrayList();
while (cells.hasNext()) {
HSSFCell cell = (HSSFCell) cells.next();
data.add(cell);
}
sheetData.add(data);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fis != null) {
fis.close();
}
}
showExcelData(sheetData);
}
private static void showExcelData(List sheetData) {
// LinkedHashMap<String, String> tableFields = new LinkedHashMap();
for (int i = 0; i < sheetData.size(); i++) {
List list = (List) sheetData.get(i);
for (int j = 0; j < list.size(); j++) {
Cell cell = (Cell) list.get(j);
if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC) {
System.out.print(cell.getNumericCellValue());
} else if (cell.getCellType() == Cell.CELL_TYPE_STRING) {
System.out.print(cell.getRichStringCellValue());
} else if (cell.getCellType() == Cell.CELL_TYPE_BOOLEAN) {
System.out.print(cell.getBooleanCellValue());
} else if (cell.getCellType()== Cell.CELL_TYPE_BLANK){
System.out.print(cell.toString());
}
if (j < list.size() - 1) {
System.out.print(", ");
}
}
System.out.println("");
}
}
}
另外我已閱讀約workbook.setMissingCellPolicy(HSSFRow.RETURN_NULL_AND_BLANK);
。這可以幫我解決我的問題嗎?
你想用空白單元格做什麼? 'option'是什麼意思? –
我的程序會讀取這些數據並將它們存儲在表格中。如果它跳過空白單元格,則數據將無法正確存儲。我想讀這個空白單元格作爲例如空白字符串,並繼續在下一個。 – dedmar