为什么上传后的excel POI无法读取,无法导入数据库。不上传的excel POI就可以读取和导入数据库呢?请看源程序!
以下是全部代码!
文件上传提交页面UploadFileExample1.jsp
------------------------------
<%@ page contentType= "text/html; charset=gb2312 " language= "java " import= "java.sql.* " errorPage= " " %>
<html>
<head>
<title> 文件上传 </title>
</head>
<body>
<form name= "form1 " method= "post " action= "AcceptUploadFile.jsp " enctype= "multipart/form-data ">
upload file:
<label>
<input type= "file " name= "upfile " size= "50 " />
</label>
<p>
<label>
<input type= "submit " name= "Submit " value= "提交 " />
</label>
</p>
</form>
</body>
</html>
--------------------------------------------------
文件上传处理页面AccepteUploadFile.jsp
----------------------------------------
<%@ page contentType= "text/html; charset=gb2312 " %>
<%@ page import= "java.io.* "%>
<%!
public String codeToString(String str)
{
String s=str;
try
{
byte tempB[]=s.getBytes( "gb2312 ");
s=new String(tempB);
return s;
}
catch(Exception e)
{
return s;
}
}
%>
<%
String userid = session.getAttribute( "username ").toString();
String tempFileName=new String( "tempFileName1 ");//接收上传的文件内容的临时文件的文件名
File tempFile1=new File( "c:/ ",tempFileName);
FileOutputStream outputFile1=new FileOutputStream(tempFile1);
InputStream fileSource1=request.getInputStream();//得到客户端提交的所有数据
byte b[]=new byte[1000];
int n;
while((n=fileSource1.read(b))!=-1)
{
outputFile1.write(b,0,n); //将得到的客户端数据写入临时文件
}
outputFile1.close();
fileSource1.close();
RandomAccessFile randomFile1=new RandomAccessFile(tempFile1, "r ");
randomFile1.readLine();//读取第一行数据
String FilePath=randomFile1.readLine();//读取第二行数据,这行数据包括了文件的路径和文件名
int position=FilePath.lastIndexOf( '\\ '); //等到文件名
String filename=codeToString(FilePath.substring(position+1,FilePath.length()-1));
randomFile1.seek(0);//重新定位指针到文件头
long forthEnterPosition=0;
int forth=1; //得到第4行回车符号的位置,这是上传文件的开始位置
while((n=randomFile1.readByte())!=-1&&(forth <=4))
if(n== '\n ')
{
forthEnterPosition=randomFile1.getFilePointer();
forth++;
}
File FileUploadDir=new File( "E:/Tomcat 5.0/webapps/sms_cnc_rs ", "upload ");
FileUploadDir.mkdir(); //生成上传文件的目录
File saveFile1=new File( "E:/Tomcat 5.0/webapps/sms_cnc_rs/upload ",userid+ ".xls ");
RandomAccessFile randomFile2=new RandomAccessFile(saveFile1, "rw ");
randomFile1.seek(randomFile1.length());
long endPosition=randomFile1.getFilePointer();//找到上传的文件数据的结束位置,即倒数第4行
int j=1;
while((endPosition> =0)&&(j <=4))
{
endPosition--;
randomFile1.seek(endPosition);
if(randomFile1.readByte()== '\n ')
j++;
}
randomFile1.seek(forthEnterPosition);
long startPoint=randomFile1.getFilePointer();
while(startPoint <endPosition-1)
{
randomFile2.write(randomFile1.readByte());
startPoint=randomFile1.getFilePointer();
}
randomFile2.close();
randomFile1.close();
tempFile1.delete();
%>
<% response.sendRedirect( "ca.jsp ");%> ---------------跳转到excel导入数据库
------------------------
调用CLASS的JSP页面ca.jsp
<%@page contentType= "text/html;charset=GB2312 "%>
<%@ page import= "poi.POITest "%>
<%
String userid = session.getAttribute( "username ").toString();
boolean connectToDB = POITest.connectDB2();
if(connectToDB){
boolean tureOrfalse = POITest.readExcelToDB2(userid); //取帐户名作为excel的文件名,传值给POI
if (tureOrfalse==true){
out.println( "数据导入成功 ");
}else{
out.println( "数据导入失败 ");
}
}else{
out.println( "连接数据库失败! ");
}
%>
------------------------------------------------
POITest.java源程序如下
package poi;
import java.io.FileInputStream;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.*;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
public class POITest {
public static Connection conn = null;
public static Statement stmt = null;
public static boolean connectDB2() {
try {
Class.forName( "org.gjt.mm.mysql.Driver ");
String url = "jdbc:mysql://localhost:3306/dstore ";
conn = DriverManager.getConnection(url, "root ", "111111 ");
stmt = conn.createStatement();
}
//捕获加载驱动程序异常
catch (ClassNotFoundException cnfex) {
System.err.println( "装载JDBC驱动程序失败。 ");
cnfex.printStackTrace();
return false;
}
//捕获连接数据库异常
catch (SQLException sqlex) {
System.err.println( "无法连接数据库 ");
sqlex.printStackTrace();
//System.exit(1); // terminate program
return false;
}
return true;
}
public static boolean readExcelToDB2(String userName) {
POIFSFileSystem fs = null;
HSSFWorkbook wb = null;
try {
fs = new POIFSFileSystem(new FileInputStream( "E:\\Tomcat 5.0\\webapps\\sms_cnc_rs\\upload\\ "+userName+ ".xls "));
wb = new HSSFWorkbook(fs);
} catch (IOException e) {
e.printStackTrace();
return false;
}
HSSFSheet sheet = wb.getSheetAt(0);
HSSFRow row = null;
HSSFCell cell = null;
String name = " ";
long aa =0;
String company = " ";
long phone =0;
long mobile =0;
String email = " ";
String zu = " ";
int rowNum, cellNum;
int i;
rowNum = sheet.getLastRowNum();
for (i = 0; i <= rowNum; i++) {
row = sheet.getRow(i);
//cellNum = row.getLastCellNum();
try{
cell = row.getCell((short) 0);
cell.setEncoding(HSSFCell.ENCODING_UTF_16);
name = cell.getStringCellValue().trim();
name=new String(name.getBytes( "GBK "), "latin1 ");
}catch(Exception e){
}
try{
cell = row.getCell((short) 1);
aa = (long) cell.getNumericCellValue();
}catch(Exception e){
}
try{
cell = row.getCell((short) 2);
cell.setEncoding(HSSFCell.ENCODING_UTF_16);
company = cell.getStringCellValue().trim();
company=new String(company.getBytes( "GBK "), "latin1 ");
}catch(Exception e){
}
try{
cell = row.getCell((short) 3);
phone = (long) cell.getNumericCellValue();
}catch(Exception e){
}
try{
cell = row.getCell((short) 4);
mobile = (long) cell.getNumericCellValue();
}catch(Exception e){
}
try{
cell = row.getCell((short) 5);
email = cell.getStringCellValue();
}catch(Exception e){
}
try{
cell = row.getCell((short) 6);
zu = cell.getStringCellValue();
}catch(Exception e){
}
String sql = "insert into listuser(username,password,email,homepage,signs,fenzu,company,mobile) values( ' "+name+ " ', ' "+phone+ " ', ' "+email+ " ', ' "+aa+ " ', ' "+userName+ " ', ' "+zu+ " ', ' "+company+ " ', ' "+mobile+ " ') ";
try {
stmt.executeUpdate(sql);
} catch (SQLException e1) {
e1.printStackTrace();
return false;
}
}
return true;
}
}
上传的excel是用用户的帐户作为文件名的!
[解决办法]
用jspsmartupload.jar
代码:
<%
response.setDateHeader( "Expires ",0);
%>
<%@page contentType= "text/html; charset=GB2312 " %>
<jsp:useBean id= "mySmartUpload " scope= "page " class= "com.jspsmart.upload.SmartUpload "/>
<jsp:useBean id= "PubOptExcel " scope= "page " class= "hnccbean.PubH1OptExcel "/>
<html>
<head>
<title>
h1opt_zdzxs
</title>
</head>
<body bgcolor= "#ffffff ">
<%
int rows = 0;
try{
mySmartUpload.initialize(pageContext);
mySmartUpload.upload();
String myFileName = " ";
String myFilePath = " ";
com.jspsmart.upload.File myFile = mySmartUpload.getFiles().getFile(0);
if (!myFile.isMissing())
{
myFileName = myFile.getFileName();
try{
myFile.saveAs( "store/ "+myFileName,mySmartUpload.SAVE_VIRTUAL);
}catch(Exception e){
System.out.println( "ddd "+e.toString());
}
}
%>
<script language= "javascript ">
alert( "成功上传 ");
</script>
<%
}catch(Exception e){
%>
<script language= "javascript ">
alert( "文件上传出错 "); </script>
<%
}
%>
</body>
</html>
[解决办法]
上传代码有问题吧,否则也不可能上传了之后就不能用了。