我想使用Apache POI从excel表中存储数据。
在该excel中,第一行包含员工信息(即员工姓名),列值包含员工详细信息(即员工地址)。
因此每个标题行(emp名称)由多列(emp地址)组成
如何获取存储在单个实体中的行和列值?
我正在使用Java Spring数据。
答案 0 :(得分:0)
假设您正在使用弹簧注释,则可以使用以下代码从Excel工作表中读取值。
@RequestMapping(value = "/excelSheetProgram")
public String excelSheetProgram(@ModelAttribute("excel"),
HttpServletRequest request, RedirectAttributes attributes, HttpServletResponse response, Object command,
BindException errors, @RequestParam("Excelfile") MultipartFile Excelfile) throws Exception {
InputStream inputStream = null;
inputStream = Excelfile.getInputStream();
XSSFWorkbook workbook = new XSSFWorkbook(new
PushbackInputStream(inputStream));
XSSFSheet mySheet = workbook.getSheetAt(0);
// boolean variable for checking when to stop execution of reading from excel fields
boolean inData = true;
Iterator<Row> rowIterator = mySheet.iterator();
rowIterator.next();
int count = 0;
for (int i = 0; rowIterator.hasNext() && inData; i++) {
count++;
Row row = rowIterator.next();
// For each row, iterate through each columns
Iterator<Cell> cellIterator = row.cellIterator();
while (cellIterator.hasNext()) {
Cell cell = cellIterator.next();
// This will change all Cell Types to String
cell.setCellType(Cell.CELL_TYPE_STRING);
switch (cell.getCellType()) {
case Cell.CELL_TYPE_BOOLEAN:
break;
case Cell.CELL_TYPE_NUMERIC:
break;
case Cell.CELL_TYPE_STRING:
break;
}
}
if (row == null || row.getCell(1) == null || row.getCell(1).getStringCellValue() == null
|| inData == false) {
inData = false;
}
else {
// getting values from excel cells
employee_name = row.getCell(0).getStringCellValue();
employee_address = row.getCell(1).getStringCellValue();
}
}