java 解析excel文件

在項目中遇到的這樣的需求,用戶需要用到導入功能,將數據通過excel文件上傳到服務器,並將數據保存到數據庫。

利用java解析excel文件:

代碼片段:

public class Test(){
protected ActionForward doAction(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) throws Exception{

ServletFileUpload upload = new ServletFileUpload(new DiskFileItemFactory());
List wj_list = upload.parseRequest(request);
java.io.InputStream in=null;
for (int i = 0; i < wj_list.size(); i++) {
FileItem fi = (FileItem) wj_list.get(i);
if (!fi.isFormField()) {
// file = fi.get();// 文件內容
 in=fi.getInputStream();
}
}
List list=new  ArrayList();
try {
//jxl.Workbook rwb = Workbook.getWorkbook(new File(
//"f:\\" + filename + ".xls"));
jxl.Workbook rwb = Workbook.getWorkbook(in);
Sheet st = rwb.getSheet(0);//得到第0個sheet
int n = st.getRows();//得到行數
int i = 1; // 開始行,從第二行開始
while (i<n) {//循環行
Test t= new Test();
//循環列
for (int j = 0; j < 4; j++) {
if (st.getCell(j, 0).getContents().equals("第一列")){
t.setPropertyOne((st.getCell(j, i).getContents()));
}
if (st.getCell(j, 0).getContents().equals("第二列")){
   t.setPropertyTwo(st.getCell(j, i).getContents());
}
if (st.getCell(j, 0).getContents().equals("第三列")){
  t.setPropertyThree(st.getCell(j, i).getContents());
}
if (st.getCell(j, 0).getContents().equals("第四列")){
t.setPropertyFour(st.getCell(j, i).getContents());
}

}
list.add(t);//將解析的每一行的對象放到一個list
i++;
}
rwb.close();
in.close();
} catch (Exception e) {
e.printStackTrace();
}
return mapping.findForward("success");
}
}

但是有一個困惑的問題是:我的excel文件中有2條數據,而解析的時候卻是有大於2條的時候,不知道是怎麼回事

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章