你好! 请教你个问题 java web程序如何将读取的excel表格里的数据插入到数据库,并显示在JSP页面上?

如题所述

主要用poi.jar åŒ…。包含两个jar就可以了:poi-3.16.jar、poi-ooxml-3.16.jar

主要方法分三步:

/**
* filePath æ–‡ä»¶è·¯å¾„
* unCaseRow  è¦æŽ’除的行数(从上往下)
* unCaseLine  è¦æŽ’除的列数(从左往右)
*/
public List<String[]> readExcel(String filePath, int unCaseRow, int unCaseLine) throws Exception {
   Sheet sheet = null;
    FileInputStream inStream = null;
try {
inStream = new FileInputStream(new File(filePath));
Workbook workBook = WorkbookFactory.create(inStream);

sheet = workBook.getSheetAt(0);
} catch (Exception e) {
e.printStackTrace();
throw new Exception();
} finally {
try {
if (inStream != null) {
inStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}

List<String[]> list = init(sheet, unCaseRow, unCaseLine);// éœ€è¦æŽ’除行数

return list;
}

// åˆå§‹åŒ–表格中的每一行,并得到每一个单元格的值
private List<String[]> init(Sheet sheet, int unCaseRow, int unCaseLine) {
int rowNum = sheet.getLastRowNum() + 1; // ä»Žé›¶å¼€å§‹
List<String[]> result = new ArrayList<String[]>();
String[] rowArr = null;

Row row = null;
Cell cell = null;
int rowLength = 0;
int rowIndex = 0;
String rowStr = null;
for (int i = unCaseRow; i < rowNum; i++) {
row = sheet.getRow(i);
// æ¯æœ‰æ–°çš„一行,创建一个新的LinkedList对象
rowLength = row.getLastCellNum();
rowIndex = 0;
rowArr = new String[LINECOUNT];
for (int j = unCaseLine; j < rowLength; j++) {
cell = row.getCell(j);
// èŽ·å–单元格的值
rowStr = getCellValue(cell);
// å°†å¾—到的值放入链表中
rowArr[rowIndex++] = rowStr;
}

result.add(rowArr);
}

return result;
}

// èŽ·å–单元格的值
@SuppressWarnings("deprecation")
private String getCellValue(Cell cell) {
String cellValue = "";
DataFormatter formatter = new DataFormatter();
if (cell != null) {
// åˆ¤æ–­å•å…ƒæ ¼æ•°æ®çš„类型,不同类型调用不同的方法
switch (cell.getCellType()) {
// æ•°å€¼ç±»åž‹
case Cell.CELL_TYPE_NUMERIC:
// è¿›ä¸€æ­¥åˆ¤æ–­ ï¼Œå•å…ƒæ ¼æ ¼å¼æ˜¯æ—¥æœŸæ ¼å¼
if (DateUtil.isCellDateFormatted(cell)) {
cellValue = formatter.formatCellValue(cell);
} else {
// æ•°å€¼
double value = cell.getNumericCellValue();
int intValue = (int) value;
cellValue = value - intValue == 0 ? String.valueOf(intValue) : String.valueOf(value);
}
break;
case Cell.CELL_TYPE_STRING:
cellValue = cell.getStringCellValue();
break;
case Cell.CELL_TYPE_BOOLEAN:
cellValue = String.valueOf(cell.getBooleanCellValue());
break;
// åˆ¤æ–­å•å…ƒæ ¼æ˜¯å…¬å¼æ ¼å¼ï¼Œéœ€è¦åšä¸€ç§ç‰¹æ®Šå¤„理来得到相应的值
case Cell.CELL_TYPE_FORMULA: {
try {
cellValue = String.valueOf(cell.getNumericCellValue());
} catch (IllegalStateException e) {
cellValue = String.valueOf(cell.getRichStringCellValue());
}

}
break;
case Cell.CELL_TYPE_BLANK:
cellValue = "";
break;
case Cell.CELL_TYPE_ERROR:
cellValue = "";
break;
default:
cellValue = cell.toString().trim();
break;
}
}
return cellValue.trim();
}

解析成对象以后,不论是插入数据库,还是jsp,都是一样的。

插入数据库:hibernate、mybatis

在jsp显示:对象封装进list,在页面显示list。

温馨提示:答案为网友推荐,仅供参考