jsp 用smartupload上传Excel文件并在后台用jxl解析数据

最近开发了上传excel文件功能并解析数据,特做此记录和分享,以备不时之需,也希望对大家有用。

本例将要实现功能:

  1. 前台jsp页面上传excel文件。
  2. 用smartupload在后台接收excel文件。
  3. 用jxl.jar读取excel文件并收集数据。

一 、 前台上传文件
先上代码

first.jsp

请选择导入文件: 

代码很简单,不过有几个小细节需要注意。

1 .jxl 貌似只能处理.xls格式的EXCEL文件,所以这里js控制了;
2. first.jsp 中上传后,页面不跳转,需要在当前页面显示出处理结果,所以 使用了 form 的target属性,本例中为 importFrame
3. 点击“导入数据”按钮后,先把按钮置为不可点,防止重复提交;


二、smartupload在后台接收excel文件

需要提前下载smartupload.jar包。

代码如下:
upload.jsp

 <%

String returnMessage = ""; //导入结果返回消息

try{
	com.jspsmart.upload.SmartUpload upload=new com.jspsmart.upload.SmartUpload();
	   upload.initialize(pageContext);
	   upload.setMaxFileSize(10000000); //限制上传文件的大小1兆
       upload.upload();//上传
	  //文件上传后的文件对象
	  com.jspsmart.upload.File myFile = upload.getFiles().getFile(0);
	  String strFileName = myFile.getFileName();
      String abspath =request.getRealPath("/")+"/myworkupload/"+strFileName;
      myFile.saveAs(abspath);
%>

这样,边接收到了前台上传的文件,保存在服务器的某个路径下。


三、JXL解析EXCEL文件

当然,使用jxl之前,还是先得下载jxl.jar包。

upload.jsp

int sheetNum=0;
File sourcefile=new File(filePath);
InputStream is = new FileInputStream(sourcefile);
jxl.Workbook rwb = Workbook.getWorkbook(is);       
Sheet rs = rwb.getSheet(sheetNum);//页

int col = rs.getColumns();//列
int row = rs.getRows();
System.out.println("(文件:"+filePath+"["+sheetNum+"页]):总共"+row+"行,"+col
列col``
);

上述代码读取excel中第一个sheet中的行数和列数,以备循环读取内容使用。

upload.jsp

List workContentList = new ArrayList();//
List detailContentList = new ArrayList();//
List belongToList = new ArrayList();//
List beginDateList = new ArrayList();//
List endDateList = new ArrayList();//
List noteList = new ArrayList();//

for(int i=0;ijsp 用smartupload上传Excel文件并在后台用jxl解析数据_第1张图片

上传成功时,上传按钮不可点:
jsp 用smartupload上传Excel文件并在后台用jxl解析数据_第2张图片

点击确定后,按钮恢复:
这里写图片描述

好了,就先分享到这。有不正之处,欢迎留言讨论。

你可能感兴趣的:(Web)