首先,本文是运用jxl进行excel表的解析,所以我们需要先下载一个jxl.jar的jar包;
并且需要一个与excel表对应的实体类,用于接收excel的数据;
然后就是代码部分,我们先编写一个函数,用于读取excel;
该函数会返回execl中的数据,将数据一个一个写入innerList,再将innerList写入outerList
最后返回outerList
public List readExcel(File file) {
try {
// 创建输入流,读取Excel
InputStream is = new FileInputStream(file.getAbsolutePath());
// jxl提供的Workbook类
Workbook wb = Workbook.getWorkbook(is);
// Excel的页签数量
int sheet_size = wb.getNumberOfSheets();
for (int index = 0; index < sheet_size; index++) {
List outerList=new ArrayList();
// 每个页签创建一个Sheet对象
Sheet sheet = wb.getSheet(index);
// sheet.getRows()返回该页的总行数
for (int i = 0; i < sheet.getRows(); i++) {
List innerList=new ArrayList();
// sheet.getColumns()返回该页的总列数
for (int j = 0; j < sheet.getColumns(); j++) {
String cellinfo = sheet.getCell(j, i).getContents();
if(cellinfo.isEmpty()){
continue;
}
innerList.add(cellinfo);
}
outerList.add(i, innerList);
}
return outerList;
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (BiffException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
然后再编写一个函数将文件的路径给解析函数,然后就可以根据解析函数返回的outerList进行循环查看表中的数据;
下面的函数中,直接将拿到的数据赋值给一个对象,然后直接给另一个与数据库连接的UserService_sadmin()类中的leading方法插入数据库。
private void leading_in() {
List u=new ArrayList();
File file = new File("G:/jifangstudent/temp/student.xls");//需要解析的excel表,注意表的格式必须为xls
List excelList = readExcel(file);
for (int i = 1; i < excelList.size(); i++) {//循环遍历List中的内容
List list = (List) excelList.get(i);
int j = 0;
if(j < list.size()) {
User user=new User();//新建一个对象,将数据循环赋值给对象
user.setUsername(list.get(0).toString());
user.setPassword(list.get(1).toString());
user.setNo(list.get(2).toString());
user.setName(list.get(3).toString());
user.setSex(list.get(4).toString());
user.setDepartment(list.get(5).toString());
user.setTelephone(list.get(6).toString());
user.setEmail(list.get(7).toString());
user.setUsertype(list.get(8).toString());
j=10;
u.add(user);//每解析一行即可得到一个对象,再将对象写到List中
}
}
boolean success=new UserService_sadmin().leading(u);//调用函数,进行数据库中数据的插入操作
}