<%@ page contentType="text/html;charset=gb2312"%> 
<%@ page import="java.io.*,jxl.*,jxl.write.*,jxl.format.*"%> 
<%@ page import="java.sql.*"%> 
<%@ page import="java.util.*"%> 
<%@ page import="com.jspsmart.upload.*"%> <%
com.jspsmart.upload.SmartUpload smartUpload = new com.jspsmart.upload.SmartUpload(); //初始化smartUPload 
smartUpload.initialize(pageContext); 
smartUpload.service(request, response);
smartUpload.upload(); 
com.jspsmart.upload.File file = smartUpload.getFiles().getFile(0); //得到上页输入的文件 System.out.println(file.getFileName());
//取中文表单参数 
String newFileName = "test.xls"; 
//改名上传 
file.saveAs("excel/" + newFileName,smartUpload.SAVE_VIRTUAL); 
%> <%!public String codeToString(String str) {//处理中文字符串的函数 
String s=null;
try
{
s=new String(str.getBytes("unicode"),"gbk");
}
catch(Exception e)
{
e.printStackTrace();
}
finally
{
return s;
}} %> 
<html> 
<head> <title></title> 
</head> 
<body> 
<%
//得到前页传过来的参数 
String courseId=session.getAttribute("courseId").toString(); 
%> 
<%String path = request.getRealPath("\\") + "excel" + "\\" 
+ "test.xls";//Excel文件URL 
InputStream is = new FileInputStream(path);//写入到FileInputStream jxl.WorkbookSettings work=new jxl.WorkbookSettings();
work.set
System.out.println(work.getEncoding());jxl.Workbook wb = Workbook.getWorkbook(is); //得到工作薄 jxl.Sheet st = wb.getSheet(0);//得到工作薄中的第一个工作表 int rsRows = st.getRows(); //得到excel的总行数 
for (int i = 1; i < rsRows; i++) { Cell cell0 = st.getCell(0, i);//得到工作表的第一个单元格,即A1 
Cell cell1 = st.getCell(1, i);//得到工作表的第二个单元格,即A1 try { 
String content0 = codeToString(cell0.getContents());//getContents()将Cell中的字符转为字符串 
int content1 = Integer.parseInt(cell1.getContents()); //得到条形码 //存入数据库 
String sql = "insert into sy_score(courseId,scoreStudentName,score)" 
+ "values(" 
+ courseId
+ ",''" 
+ content0 
+ "''," 
+ content1+")"; 
System.out.println(sql); //输出时中文是乱码,其余都正常.为什么?
//common.Del_Insert(sql); //执行SQL语句
} catch (Exception e) { 
//如果EXCEL文件中输入的数据有错,则跳过此行数据 
session.setAttribute("message", "有错误,不能导入,请检查您的excel文件"); 
continue; 


wb.close();//关闭工作薄 
is.close();//关闭输入流 
response.sendRedirect("insert_done.jsp"); //转到成功页
%> 
</body> 
</html>

解决方案 »

  1.   

    可能我说的不清楚,
    譬如excel里有个单元格里是中文字段,可是我取出来在日志里显示是乱码!
    换了字符编码也不行!大家帮帮忙!
      

  2.   

    你这个方法有问题:
    public String codeToString(String str) {//处理中文字符串的函数 
    String s=null; 
    try 

    s=new String(str.getBytes("unicode"),"gbk"); 

    catch(Exception e) 

    e.printStackTrace(); 

    finally 

    return s; 
    } } 
    你确定从excel里取出的是unicode编码的,不是的话肯定是乱码了,你可以试试改一下编码或者直接去掉这个方法
      

  3.   

    我的资源里有个java解析excel源码,下载后即可使用,有兴趣得朋友可以去看看