準備:jxl.jar,jspsmartupload.jar 兩個包 excel表格
1.上傳excel獲得路徑
SmartUpload su=new SmartUpload();
su.initialize(this.getServletConfig(), request, response);try {
su.upload();
String strname=su.getFiles().getFile(0).getFileName();
String abPath=this.getServletContext().getRealPath("/kejian");
//3.設定允許上傳的文件(通過擴展名限制),僅允許doc、txt文件.
su.setAllowedFilesList("xls");
//4.設定禁止上傳的文件(通過擴展名限制),禁止上傳帶有exe、bat、jsp、htm、html擴展名的文件和沒有擴展名的文件
su.setDeniedFilesList("ext,bat,jsp,htm,html,txt,doc,pdf,,");
String filepath=abPath+File.separator+strname;
su.getFiles().getFile(0).saveAs(filepath);
escelTeachStu(filepath);
request.getRequestDispatcher("teacher/excelupload.jsp").forward(request, response);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//通過excel路徑獲得數據並寫到數據庫
public void escelTeachStu(String filepath){
try {
Workbook book = Workbook.getWorkbook(new File(file));
Sheet sheet = book.getSheet( 0 );
int rows = sheet.getRows();
int cols = sheet.getColumns();
TeachStuImp st=new TeachStuImp();
for (int x = 1; x <rows; x++) {
List<String>list=new ArrayList<String>();
for (int j = 0; j < cols; j++) {
Cell xy = sheet.getCell(j, x);
list.add(xy.getContents());
}
// 將數據插入數據庫表
TeachStu am=new TeachStu(list.get(0),list.get(1),list.get(2));st.add(am);
}
} catch (BiffException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}