將Excel文件內容寫入到數據庫
public class EStudentInsertExcelController extends SimpleFormController {

private IStudent_infoManage studentManage;

@Override
protected ModelAndView onSubmit(HttpServletRequest request,
HttpServletResponse response, Object command, BindException errors)
throws Exception {
Student_info student_info = (Student_info) command;
try {
MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
MultipartFile file = multipartRequest.getFile( " Excelfile " ); // 獲得文件:
File toFile = new File( " c:\\學生信息臨時文件.xls " ); // 產生文件名和空文件
file.transferTo(toFile); // 文件上傳
Workbook book = Workbook.getWorkbook(toFile); // 得到工作薄
Sheet sheet = book.getSheet( 0 ); // 獲得第一個工作表對象
int row = sheet.getRows(); // /得到該sheet的行數
int column = sheet.getColumns(); // 得到該sheet的列數
System.out.println( " 數據行數= " + row);
System.out.println( " 數據列數= " + column);
for ( int i = 1 ;i < row;i ++ )
{
for ( int j = 0 ;j < column;j ++ )
{
System.out.println( " j= " + j);
sheet.getCell(j, i).getContents(); // 得到第j列第i行的單元格的類容
student_info.setStudentID(sheet.getCell(j, i).getContents());
student_info.setName(sheet.getCell( ++ j,i).getContents());
student_info.setSex(sheet.getCell( ++ j,i).getContents());
student_info.setUnit(sheet.getCell( ++ j,i).getContents());
student_info.setClass_(sheet.getCell( ++ j,i).getContents());
student_info.setSpecialty(sheet.getCell( ++ j,i).getContents());
student_info.setRemark(sheet.getCell( ++ j,i).getContents());
}
if ( this .studentManage.getStudentByStudentID(
student_info.getStudentID()).size() != 0 )
return new ModelAndView( " education/e-studentInfoAddError " );
this .studentManage.insertStudent_info(student_info);
}
book.close();
return new ModelAndView( " education/e-studentInfoAddExcelSuccess " , " row " , new Integer(row - 1 ));
} catch (Exception e) {
e.printStackTrace();
}
return new ModelAndView( " education/e-studentInfoAddExcelError " );
}
public void setStudentManage(IStudent_infoManage studentManage) {
this .studentManage = studentManage;
}
}


















































posted on 2011-11-16 14:12 Steven_bot 閱讀(349) 評論(0) 編輯 收藏 所屬分類: tools