【发布时间】:2015-06-22 06:49:51
【问题描述】:
我有一个 .xlsx 格式的 Excel 文件。我通过合并单元格以形成各种列来存储数据。我正在通过 Java Web 应用程序读取 Excel 文件并将其数据保存到数据库 (MySQL)。但是当我从合并的单元格中读取时,我会得到空值以及存储在列和标题中的内容。我正在使用 Apache POI。我的代码是:
public static void excelToDBLogIN() {
FileInputStream file = null;
Boolean flag = true;
ArrayList<String> rows = new ArrayList<String>();
try {
// here uploadFolder contains the path to the Login 3.xlsx file
file = new FileInputStream(new File(uploadFolder + "Login 3.xlsx"));
//Create Workbook instance holding reference to .xlsx file
XSSFWorkbook workbook = new XSSFWorkbook(file);
//Get first/desired sheet from the workbook
XSSFSheet sheet = workbook.getSheetAt(0);
//Iterate through each rows one by one
Iterator<Row> rowIterator = sheet.iterator();
while (rowIterator.hasNext()) {
Row row = rowIterator.next();
//For each row, iterate through all the columns
Iterator<Cell> cellIterator = row.cellIterator();
String tuple = "";
while (cellIterator.hasNext()) {
Cell cell = cellIterator.next();
//Check the cell type and format accordingly
switch (cell.getCellType()) {
case Cell.CELL_TYPE_NUMERIC:
//int value = new BigDecimal(cell.getNumericCellValue()).setScale(0, RoundingMode.HALF_UP).intValue();
//tuple = tuple + String.valueOf(value) + "+";
DataFormatter objDefaultFormat = new DataFormatter();
String str = objDefaultFormat.formatCellValue(cell);
tuple = tuple + str + "+";
break;
case Cell.CELL_TYPE_STRING:
tuple = tuple + cell.getStringCellValue() + "+";
break;
case Cell.CELL_TYPE_BLANK:
tuple = tuple + "" + "+";
break;
}
}
rows.add(tuple);
flag = true;
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (file != null) {
try {
file.close();
file = null;
} catch (Exception e) {
System.out.println("File closing operation failed");
e.printStackTrace();
}
}
}
}
}
我在网上搜索了答案,但没有找到任何相关内容。
【问题讨论】:
-
合并的单元格很糟糕,很糟糕,不应该被允许。避开他们。 Excel 通常会将合并范围的内容存储在该范围的左上角单元格中。所有其他单元格返回 0。
-
我知道,但 Excel 的格式是由大学部门制定的。我们的项目只是从他们那里获取信息并更新数据库。我个人会避免这些。
-
@teylyn 合并单元格不好有什么特别的原因吗?
-
@EMM 是的。他们让事情变得不安。将 A3 合并到 D3。现在尝试选择 C1 到 C5。或者使用循环将某些内容写入 C1 到 C5。看看为什么不好?
标签: java apache apache-poi cell import-from-excel