此处需要导入两个包,一个是commons-fileupload-1.2.1.jar 另一个是jxl-2.6.jar
以下为excel_upload.jsp处理页面
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%@ page import="java.io.*"%>
<%@ page import="javax.servlet.*"%>
<%@ page import="javax.servlet.http.*"%>
<%@ page import="java.sql.*" %>
<%@ page import="java.text.*"%>
<%@ page import="org.apache.commons.fileupload.DefaultFileItemFactory"%>
<%@ page import="org.apache.commons.fileupload.FileItemFactory"%>
<%@ page import="org.apache.commons.fileupload.FileItemIterator"%>
<%@ page import="org.apache.commons.fileupload.FileItemStream"%>
<%@ page import="org.apache.commons.fileupload.disk.DiskFileItemFactory"%>
<%@ page import="org.apache.commons.fileupload.servlet.ServletFileUpload"%>
<%@ page import="org.apache.commons.fileupload.util.Streams"%>
<%@ page import="xt.servlets.Customer"%>
<%@ page import="jxl.*"%>
<jsp:useBean id="DBManage" class="publib.dbmng.DBManage" scope="page"></jsp:useBean>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<% File tmpDir = null;//初始化上传文件的临时存放目录
File saveDir = null;//初始化上传文件后的保存目录
Workbook rwb=null;
int sheets=0;//excel文件中所含的Sheet表数量
int rsRows=0;//Sheet表的行数
int rsColumns=0;//Sheet表的行数
int cell_length=0;
List<String> list1=new ArrayList<String>();
List<String> list2=new ArrayList<String>();
String [] ss1;
String ss2=null;
Connection con=null;
PreparedStatement ps = null;
DBManage.setAutoCommit(false);
String sql="insert into loan.customer_djxx (customer_id,customer_date,customer_result) values(?,?,?)";
String sqlstr2="";
int sqlrs2;
Calendar now=Calendar.getInstance();
String time=now.get(Calendar.YEAR)+"-"+(now.get(Calendar.MONTH)+1)+"-"+now.get(Calendar.DAY_OF_MONTH)+"#"+now.get(Calendar.HOUR_OF_DAY)+"时"+now.get(Calendar.MINUTE)+"分"+now.get(Calendar.SECOND)+"秒";
SimpleDateFormat dateFormat=new SimpleDateFormat("yyyy-MM-dd");
String filepath = request.getSession().getServletContext().getRealPath("/");
String tmpPath =filepath+"tmpdir";
String savePath =filepath+"updir";
tmpDir = new File(tmpPath);
saveDir = new File(savePath);
if(!tmpDir.isDirectory())
tmpDir.mkdir();
if(!saveDir.isDirectory())
saveDir.mkdir();
String fileName="";
//上传文件到工程目录下
try{
if(ServletFileUpload.isMultipartContent(request)){
DiskFileItemFactory dff = new DiskFileItemFactory();//创建该对象
dff.setRepository(tmpDir);//指定上传文件的临时目录
dff.setSizeThreshold(1024000);//指定在内存中缓存数据大小,单位为byte
ServletFileUpload sfu = new ServletFileUpload(dff);//创建该对象
//sfu.setFileSizeMax(5000000);//指定单个上传文件的最大尺寸
sfu.setSizeMax(10000000);//指定一次上传多个文件的总尺寸
FileItemIterator fii = sfu.getItemIterator(request);//解析request 请求,并返回FileItemIterator集合
while(fii.hasNext()){
FileItemStream fis = fii.next();//从集合中获得一个文件流
if(!fis.isFormField() && fis.getName().length()>0){//过滤掉表单中非文件域
fileName = fis.getName().substring(fis.getName().lastIndexOf("\\"));//获得上传文件的文件名
fileName=fileName.substring(fileName.indexOf("\\"),fileName.indexOf("."))+time+fileName.substring(fileName.indexOf("."));
if(!fileName.substring(fileName.indexOf(".")).contains("xls")){
out.println("<SCRIPT language='JavaScript'>");
out.println("window.alert('文件格式不正确');");
out.println("window.location='/Loan/xypj/save.jsp';");
//out.println("window.location='/Loan/khgl/S1516tzkhlb0.jsp?khbh="+khbh+"';");
out.println("</SCRIPT>");
return;
}
BufferedInputStream in = new BufferedInputStream(fis.openStream());//获得文件输入流
BufferedOutputStream outt = new BufferedOutputStream(new FileOutputStream(new File(saveDir+fileName)));//获得文件输出流
Streams.copy(in, outt, true);//开始把文件写到你指定的上传文件夹
}
}
//解析上传好的excel文件,并将其中的字段与数据库中的表的字段相对应保存
try
{
//构建Workbook对象, 只读Workbook对象
//直接从本地文件创建Workbook
//从输入流创建Workbook
//InputStream is = new FileInputStream(saveDir+fileName);
//jxl.Workbook rwb = Workbook.getWorkbook(is);
con = DBManage.getCon();
con.setAutoCommit(false);
rwb = Workbook.getWorkbook(new File(saveDir+fileName));
sheets = rwb.getNumberOfSheets(); //此excel中包含几张Sheet表
for(int i=0;i<sheets;i++){
Sheet rs = rwb.getSheet(i); //获取第i个Sheet表
rsRows = rs.getRows(); //获得Sheet表中的总行数
rsColumns = rs.getColumns(); //获得Sheet表中的总列数
ArrayList<Customer> list=new ArrayList<Customer>();//存放从excel表中读出每一行的customer对象
for(int h=1;h<rsRows;h++){//分别获取每一行记录,并将其加入到list链表中
Cell[] cl=rs.getRow(h);
cell_length=cl.length;
if(cl[0].getContents()!=null&&cl[1].getContents()!=null&&cl[1].getContents()!=""){
ss1=cl[1].getContents().trim().substring(0,10).split("/");//将从excel中得到的日期数据(2010//01/02)转换成(2010-01-02)
ss2=ss1[0]+"-"+ss1[1]+"-"+ss1[2];
Customer c=new Customer(cl[0].getContents().trim(),ss2,cl[2].getContents().trim());
list.add(c);//存入到list链表中
}else{
//out.println("<SCRIPT language='JavaScript'>");
//out.println("window.alert('"+rs.getName()+"工作表中包含空值');");
//out.println("window.location='/Loan/donglin_test/save.jsp';");
//out.println("window.location='/Loan/khgl/S1516tzkhlb0.jsp?khbh="+khbh+"';");
//out.println("</SCRIPT>");
continue;
}
}
//for(Customer l : list){
try{
ps = con.prepareStatement(sql);
System.out.println("开始:"+new java.util.Date());
for(int m=0;m<list.size();m++){//遍历list链表,存入到数据库
Customer cus=list.get(m);
sqlstr2="select customer_id,customer_date from loan.customer_djxx where customer_id='"+cus.getId().trim()+"'and customer_date='"+cus.getDate().trim()+"'";
sqlrs2=DBManage.sqlQueryCount(sqlstr2);
if(sqlrs2!=0){
DBManage.sqlUpdate("delete from loan.customer_djxx where customer_id='"+cus.getId().trim()+"' and customer_date='"+cus.getDate().trim()+"'");
}
ps.setString(1,cus.getId().trim());
//cc1=cus.getId().length();
ps.setString(2,cus.getDate().trim());
// cc2=cus.getDate().length();
ps.setString(3,cus.getResult().trim());
//cc3=cus.getResult().length();
ps.addBatch();
if(m0==0){
ps.executeBatch();
}
}
ps.executeBatch();
con.commit();
System.out.println("结束:"+new java.util.Date());
list1.add(rs.getName());
out.println("<SCRIPT language='JavaScript'>");
out.println("window.alert('"+rs.getName()+"工作表上传保存成功');");
//out.println("window.location='/Loan/donglin_test/save.jsp';");
//out.println("window.location='/Loan/khgl/S1516tzkhlb0.jsp?khbh="+khbh+"';");
out.println("</SCRIPT>");
}catch(Exception e){
list2.add(rs.getName());
out.println("<SCRIPT language='JavaScript'>");
out.println("window.alert('"+rs.getName()+"工作表保存失败');");
//out.println("window.location='/Loan/donglin_test/save.jsp';");
//out.println("window.location='/Loan/khgl/S1516tzkhlb0.jsp?khbh="+khbh+"';");
out.println("</SCRIPT>");
e.printStackTrace();
try{
if(con!=null){
con.rollback();
System.out.println("donglin-------工作表保存失败,rollback");
}
}catch(Exception ex){
ex.printStackTrace();
break;
}
}finally{
}
}
//}
}
catch (Exception e)
{
e.printStackTrace();
} finally{
try{
if(DBManage!=null){
DBManage.close();
System.out.println("donglin-----------数据库连接关闭");
}
if(rwb!=null){
rwb.close();
}
}catch(Exception e){
e.printStackTrace();
}
System.out.println("donglin---------读取excel文件以及存到数据库表中此过程完成");
}
//response.getWriter().println("上传文件成功!!!");//终于成功了,还不到你的上传文件中看看,你要的东西都到齐了吗
}
}catch(Exception e){
//response.getWriter().println("上传文件失败!!!");
out.println("<SCRIPT language='JavaScript'>");
out.println("window.alert('上传文件失败');");
out.println("window.location='/Loan/xypj/save.jsp';");
out.println("</SCRIPT>");
e.printStackTrace();
}
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'excel_upload.jsp' starting page</title>
<META http-equiv="Content-Type" content="text/html; charset=gb2312">
<META http-equiv="Content-Style-Type" content="text/css">
<META name="GENERATOR" content="IBM WebSphere Page Designer V4.0 for Windows">
<LINK rel="stylesheet" href="/Loan/theme/Master.css" type="text/css">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</head>
<body>
<%--<%=path %><br>
<%=basePath%><br>
服务器的工程路径<%=filepath %><br>
临时保存路径<%=tmpPath %><br>
保存路径<%= savePath%><br>
上传后保存的文件名<%=fileName %><br>
所含Sheet表数<%=sheets%><br>
总行数<%=rsRows%><br>
总列数<%=rsColumns%><br>
一行中所包含的单元格个数<%=cell_length %><br>
--%><%--
<h4> 上传成功的工作表总数<%=list1.size()%>,分别为:
<font face=宋体 color=black size=5>
<%
for(String s :list1){
out.print(s);
out.print("---^_^---");
}
%></font></h4>
<br>
--%>
<% if(list2.size()!=0){ %>
<h4> 上传失败的工作表总数<%=list2.size() %>,分别为:
<font face=宋体 color=crimson size=5>
<%
for(String s:list2){
out.print(s+" ");
}
%></font></h4>
<%}else { %>
<font face=宋体 color=green size=5>客户等级保存成功</font><br>
<%} %>
<br>
<%--<% out.println("<SCRIPT language='JavaScript'>");
out.println("window.location='/Loan/xypj/save.jsp';");
out.println("</SCRIPT>");%>
--%></body>
<h3><a href="/Loan/xypj/save.jsp">返回</a></h3>
</html>