将excel文件从jsp页面导入到数据库,先将文件上传到server,然后读取,最后删除掉
上传
//要加encType="multipart/form-data"
<form action="addmore_project.jsp" name="muti" method="post" encType="multipart/form-data">
批量导入项目<input type=file name="daoru" >
<input type=button value="提交" class=buttons >
</form>
<%@ page import="java.sql.*" c%>
<%@ page import="web.CommFunc,web.OperateExcel"%>
<%@ page import="com.jspsmart.upload.*"%>
<%request.setCharacterEncoding("UTF-8");%>
<%
// 新建一个SmartUpload对象/////////******先将文件上传至server
SmartUpload su = new SmartUpload();
// 上传初始化
su.initialize(pageContext);
// 上传文件
su.upload();
//假设有request.getParameter()应该放在su.upload()的后面,否则报错
String filePath = request.getParameter("daoru");
try{
Class.forName(db_forname);
Connection conn= DriverManager.getConnection(db_url,db_user,db_password);
String FilePath = "";
String filename="";
if (su.getFiles().getCount()>0) {
com.jspsmart.upload.File file = su.getFiles().getFile(0);
FilePath = "/upload/temp/";
filename = file.getFileName();
java.io.File f = new java.io.File(application.getRealPath("/")+FilePath);
if(!f.exists()){
f.mkdirs();
}System.out.println(FilePath + filename);
file.saveAs(FilePath + filename);
}
else {
out.println("没有上传文件,请[<a href=‘javascript:history.back();‘>返回</a>]");
}
///////////////////////////////////////////////////
OperateExcel oe = new OperateExcel();
//oe.save_project(oe.readExecel(filePath),conn);
oe.save_projectFive(oe.readExecelFive(application.getRealPath("/")+FilePath + filename),conn);
out.println("<center><span>批量导入成功</span></center>");
//******最后将这个文件删除
java.io.File f1 = new java.io.File(application.getRealPath("/")+FilePath + filename);
if(f1.exists()){
f1.delete();
}
%>
文件下载
<%@ page import="java.sql.*,com.jspsmart.upload.*" c%> // 新建一个SmartUpload对象
SmartUpload su = new SmartUpload();
// 初始化
su.initialize(pageContext);
// 设定contentDisposition为null以禁止浏览器自己主动打开文件,
//保证点击链接后是下载文件。若不设定,则下载的文件扩展名为
//doc时,浏览器将自己主动用word打开它。扩展名为pdf时,
//浏览器将用acrobat打开。
su.setContentDisposition(null);
// 下载文件
su.downloadFile(filename);
//以下两句重要,否则有可能会提示出错:
//java.lang.IllegalStateException: getOutputStream() has already been called for this response
//这个错误的其他解决方法:就是文件開始的<%%>都要紧挨着,不能有空格,更不能有换行,如:
//http://dl2.csdn.net/down4/20070717/17095956994.rarhttp://dl2.csdn.net/down4/20070717/17095956994.rar<%@ page contentType="text/html; charset=GBK" %><%@ page import="java.io.*" %><%
out.clear();
out = pageContext.pushBody();
}
catch (Exception e) {
out.println(e.getMessage());
}
%>