【发布时间】:2014-11-24 04:30:30
【问题描述】:
我有 excel 文件,代码工作正常,但是如何以不同的方式获取每列和行的值,以便我可以将值存储在数据库中。提前谢谢你
public class excel_demo {
public static void main(String[] args) {
try {
FileInputStream file = new FileInputStream(new File("C:\\Users\\Admin\\Downloads\\ExcelDemosWithPOI\\howtodoinjava_demo.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();
while (cellIterator.hasNext()) {
Cell cell = cellIterator.next();
//Check the cell type and format accordingly
switch (cell.getCellType()) {
case Cell.CELL_TYPE_NUMERIC:
System.out.print(cell.getNumericCellValue() + "\t");
break;
case Cell.CELL_TYPE_STRING:
System.out.print(cell.getStringCellValue() + "\t");
break;
}
}
System.out.println("");
}
file.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
【问题讨论】:
-
每列和行的值不同是什么意思?
-
你的意思是你想按行+单元格获取,而不仅仅是迭代?如果是这样,你是try looking at the Apache POI documentation on fetching cells吗?
-
是的,我想获取每一行+单元格,因为我想将值存储在数据库中。
-
你的代码不是已经在读取每一行和每一单元格了吗?
标签: java excel apache-poi