功能:将excel表格的数据添加到数据库中
1、excel表格数据如下图:
学号
姓名
性别
出生日期
民族
1001021045
test1
女
2014/4/1
汉族
1001021046
test2
男
2014/4/1
汉族
2、 导入代码
public void importExcelData() {
Session session = HibernateFactory.currentSession();
Workbook book = Workbook.getWorkbook(new File(filePath));
Sheet sheet = book.getSheet(0);//获得第一个工作表对象
int columnNumber = sheet.getColumns();//获取工作表的所有列数
int rowNumber = sheet.getRows();//获取工作表的所有行数
String[] functionName = new String[columnNumber];
for (int i = 0; i < functionName.length; i++) {
functionName[i] = sheet.getCell(i, 0).getContents();
}
Date tempDate = null;
for (int i = 1; i < rowNumber; i++) {
SchoolfellowData s = new SchoolfellowData();
for (int j = 0; j < columnNumber; j++) {
String result = "";
Cell cell1 = sheet.getCell(j, i);
if (cell1.getType() == CellType.DATE) {
DateCell dateCell = (DateCell) cell1;
Date date = dateCell.getDate();
result = new SimpleDateFormat("yyyy-MM-dd").format(date);
} else {
result = cell1.getContents();
}
if (functionName[j].trim().equals("学号")) {
s.setEntranceYear(result.trim());
}
if (functionName[j].trim().equals("姓名")) {
s.setEntranceYear(result.trim());
}
if (functionName[j].trim().equals("性别")) {
s.setEntranceYear(result.trim());
}
if (functionName[j].trim().equals("出生日期")) {
s.setEntranceYear(result.trim());
}
if (functionName[j].trim().equals("民族")) {
s.setEntranceYear(result.trim());
}
}
session.save(s);
}
}