Java 通过POI读取空白xls单元格
我试图读取xls文件的空单元格,并将它们作为空条目移植到我的对象xls。但我不认为这些细胞是空白的。有人能告诉我我做错了什么吗Java 通过POI读取空白xls单元格,java,apache-poi,Java,Apache Poi,我试图读取xls文件的空单元格,并将它们作为空条目移植到我的对象xls。但我不认为这些细胞是空白的。有人能告诉我我做错了什么吗 private boolean lerArquivo(String dir) throws IOException { HSSFWorkbook wb = null; HSSFRow row = null; HSSFCell cell = null; String path = dir; boolean flag = false
private boolean lerArquivo(String dir) throws IOException {
HSSFWorkbook wb = null;
HSSFRow row = null;
HSSFCell cell = null;
String path = dir;
boolean flag = false;
InputStream inp = new FileInputStream(path);
wb = new HSSFWorkbook(inp);
HSSFSheet sheet = wb.getSheetAt(0);
for (Iterator rit = (Iterator) sheet.rowIterator(); rit.hasNext();) {
row = (HSSFRow) rit.next();
for (Iterator cit = (Iterator) row.cellIterator(); cit.hasNext();) {
cell = (HSSFCell) cit.next();
switch (cell.getCellType()) {
case HSSFCell.CELL_TYPE_STRING:
xls.add(cell.getRichStringCellValue().getString());
break;
case HSSFCell.CELL_TYPE_BLANK:
xls.add(null);
break;
case HSSFCell.CELL_TYPE_NUMERIC:
if (DateUtil.isCellDateFormatted(cell)) {
xls.add(cell.getDateCellValue().toString());
} else {
xls.add(String.valueOf(cell.getNumericCellValue()));
}
break;
default:
}
}
}
编辑01-
你好,Gagravarr,谢谢你的帮助。
我尝试了你的建议,并阅读了文档。
根据我的理解,我更改了代码,达到以下目的:
即使这样,代码也不会读取空白单元格。猜猜看
for (int rowNum = 0; rowNum < 4; rowNum++) {
row = sheet.getRow(rowNum);
for (int celNum = 0; celNum < row.getLastCellNum(); celNum++) {
cell = row.getCell(celNum, org.apache.poi.ss.usermodel.Row.RETURN_BLANK_AS_NULL);
switch (cell.getCellType()) {
case HSSFCell.CELL_TYPE_STRING:
xls.add(cell.getRichStringCellValue().getString());
break;
case HSSFCell.CELL_TYPE_BLANK: {
xls.add("");
break;
}
case HSSFCell.CELL_TYPE_NUMERIC:
if (DateUtil.isCellDateFormatted(cell)) {
xls.add(cell.getDateCellValue().toString());
} else {
xls.add(String.valueOf(cell.getNumericCellValue()));
}
break;
default:
}
}
}
for(int-rowNum=0;rowNum<4;rowNum++){
row=sheet.getRow(rowNum);
对于(int-celNum=0;celNum
Apache POI已经发布,建议您阅读
从那里复制和粘贴示例,您可以看到如何处理/检测丢失的行和单元格以及空白单元格:
// Decide which rows to process
int rowStart = Math.min(15, sheet.getFirstRowNum());
int rowEnd = Math.max(1400, sheet.getLastRowNum());
for (int rowNum = rowStart; rowNum < rowEnd; rowNum++) {
Row r = sheet.getRow(rowNum);
int lastColumn = Math.max(r.getLastCellNum(), MY_MINIMUM_COLUMN_COUNT);
for (int cn = 0; cn < lastColumn; cn++) {
Cell c = r.getCell(cn, Row.RETURN_BLANK_AS_NULL);
if (c == null) {
// The spreadsheet is empty in this cell
} else {
// Do something useful with the cell's contents
}
}
}
//决定要处理的行
int rowStart=Math.min(15,sheet.getFirstRowNum());
int rowEnd=Math.max(1400,sheet.getLastRowNum());
对于(int-rowNum=rowStart;rowNum
尝试调试以查看迭代器返回的单元格。您希望为空的单元格可能根本不存在。例如,当您希望3为空时,您可能会看到列索引为0、1、2、4的单元格
s。谢谢您的提示。我尝试了“RETURN\u BLANK\u AS\u NULL”,但没有成功=/你说的“unsuccessfully”是什么意思?它在大量ApachePOI单元测试中都非常成功,尤其是在其他测试中!到底什么不起作用?对不起,起作用了。显然,问题出在libre office创建的xls中。