我正在制作一个程序,用于从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