我需要读取 Excel 文件的内容并将其转储到文本文件中。我能够从文件中读取内容。 我创建了一个 List excelData = new ArrayList(); ,它应该保存 Excel 工作表中存在的行数据。但每一列都有不同的数据类型。如何将内容保存到列表中?
List excelData = new ArrayList();
try {
FileInputStream file = new FileInputStream(new File("H:\\Docs\\Medical Data Record\\MedicalRecord2015.xlsx"));
XSSFWorkbook wb = new XSSFWorkbook(file);
XSSFSheet ws = wb.getSheetAt(0);
Iterator<Row> itr = ws.iterator();
while (itr.hasNext()) {
Row row = itr.next();
Iterator<Cell> itrCell = row.cellIterator();
while (itrCell.hasNext()) {
Cell cell = itrCell.next();
switch (cell.getCellType()) {
case Cell.CELL_TYPE_NUMERIC:
double val = cell.getNumericCellValue();
break;
case Cell.CELL_TYPE_STRING:
String txtval = cell.getStringCellValue();
break;
}
}
}
谢谢
最佳答案
看来你不需要List
,但是List<List<Object>>
这里:
List<List<Object>> excelData = new ArrayList<>();
try {
//...
while (itr.hasNext()) {
Row row = itr.next();
List<Object> dataRow = new ArrayList<>();
excelData.add(dataRow);
Iterator<Cell> itrCell = row.cellIterator();
while (itrCell.hasNext()) {
Cell cell = itrCell.next();
if (cell == null) {
dataRow.add(null);
continue;
}
switch (cell.getCellType()) {
case Cell.CELL_TYPE_NUMERIC:
dataRow.add(cell.getNumericCellValue());
break;
case Cell.CELL_TYPE_STRING:
dataRow.add(cell.getStringCellValue());
break;
case Cell.CELL_TYPE_BOOLEAN:
dataRow.add(cell.getBooleanCellValue());
break;
case Cell.CELL_TYPE_BLANK:
dataRow.add("");
break;
default:
dataRow.add(cell);
}
}
}
现在,excelData
包含List
表示为 List<Object>
的行数,并且可以轻松地逐行保存到文本文件。为了获得更好的一致性,您还需要检查其他类型的单元格,例如 Cell.CELL_TYPE_BOOLEAN
或null
.
关于java - 将excel的内容写入文本文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29900850/