Java操作Jxl实现数据交互。三部曲——《第二篇》
java操作jxl实现.xsl及.xsls两种数据表格进行批量导入数据到sql server数据库。
本文实现背景web项目:前台用的框架是easyui+bootstrap结合使用,需要引入相应的js、css文件。页面:jsp、拦截请求:servlet、逻辑处理:classbean、数据库:sqlserver。
注:bean中操作sql语句进行处理是公司内部方法,可替换为其它方法自行扩展!主要看代码逻辑业务处理!
首先我们看见easyui中的datagrid数据网格列表中没有任何数据:
其次创建一个xsl文件以下是需要导入的数据格式:
让我们把注意力放到sqlserver数据库:
点击导入按钮后弹出一个窗口选择我们刚刚创建的excel文件,最后点击导入
导入成功此时此刻easyui中的datagrid数据网格中已有了7条我们之前创建的记录!
我们回到数据库进行查看数据,果然和预期效果一样与excel表格数据一致证明导入成功!
jsp代码:
注:from中的enctype="multipart/form-data"属性是必加的,要想进行上传必须使用html中的文件控件,且必须使用enctype进行分装,表示将表单按照二进制的方式提交。即所有的操作表单此时不再是分别提交,否则将所有内容都按照二进制的方式提交。如果要上传文件,表单则必须封装。但是当一个表单使用了enctype="multipart/form-data"
封装后,其它的非表单控件的内容就无法通过
request内置对象获取,此时在servlet中必须调用smartupload类中提供的getrequest()方法获取全部的请求参数
<!doctype html public "-//w3c//dtd html 4.01 transitional//en"> <%@page language="java" contenttype="text/html; charset=utf-8" pageencoding="utf-8"%> <%@ page import="com.pantech.base.common.tools.mytools"%> <%@ page import="com.pantech.base.common.tools.publictools"%> <%@ page import="com.pantech.src.develop.logs.*"%> <%@ page import="com.pantech.base.common.tools.*"%> <%@ page import="com.pantech.src.develop.store.user.*"%> <%@ page import="com.pantech.src.develop.manage.workremind.workremind"%> <%@ page import="java.util.vector"%> <%@ page import="java.util.*"%> <%@ page import="java.text.*"%> <%@ page import="com.pantech.base.common.db.dbsource"%> <html> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8"> <title>导入</title> <link rel="stylesheet" type="text/css" href="<%=request.getcontextpath()%>/css/themes/default/easyui.css"> <link rel="stylesheet" type="text/css" href="<%=request.getcontextpath()%>/css/themes/icon.css"> <link charset="utf-8" rel="stylesheet" href="<%=request.getcontextpath()%>/css/bootstrap.css"/> <link charset="utf-8" rel="stylesheet" href="<%=request.getcontextpath()%>/css/naber.css"/> <link charset="utf-8" rel="stylesheet" href="<%=request.getcontextpath()%>/css/font-awesome/css/font-awesome.css"> <link charset="utf-8" rel="stylesheet" href="<%=request.getcontextpath()%>/css/sms-index.css"/> <link charset="utf-8" rel="stylesheet" href="<%=request.getcontextpath()%>/css/listpage.css"/> <script type="text/javascript" src="<%=request.getcontextpath()%>/script/jqueryui/jquery.min.js"></script> <script type="text/javascript" src="<%=request.getcontextpath()%>/script/jqueryui/jquery.easyui.min.js"></script> <script type="text/javascript" src="<%=request.getcontextpath()%>/script/jqueryui/locale/easyui-lang-zh_cn.js"></script> <script charset="utf-8" src="<%=request.getcontextpath()%>/script/bootstrap.min.js"></script> <script charset="utf-8" src="<%=request.getcontextpath()%>/script/layer/layer.js"></script> <script type="text/javascript" src="<%=request.getcontextpath()%>/script/common/clientscript.js"></script> <script type="text/javascript" src="<%=request.getcontextpath()%>/script/common/publicscript.js"></script> </head> <body> <%-- 遮罩层 --%> <div id="divpagemask4" class="maskstyle"> <div id="maskfont2"></div> </div> <div class="bg-box indexbox" style="width: 1000px;"> <div class="box"> <div class="manage-list"> <div class="row"> <div class="col-lg-6 col-md-6 col-sm-6 col-xs-12"> <span>个人信息列表</span> </div> <input type="button" onclick="dotoolbar(this.id);" id="importtjxx"class="btn form-control btn-success" value="体检信息批量导入"style="width: 135px; margin-top: 3px;" /> <input type="button" onclick="dotoolbar(this.id);" id="deletetjxx"class="btn form-control btn-danger" value="全部删除"style="width: 135px; margin-top: 3px;" /> </div> </div> </div> <div id="tablediv" class="tablelist"style="width: 100%; height: 600px;"> <table id="list" width="100%"></table> </div> </div> <!-- 弹窗 --> <div id="importinfodialog"> <div class="col-lg-10 col-md-10 col-sm-12 col-xs-12 content" style="width:100%;padding-top: 30px;"> <div class="content-border"> <div id="querybox2"> <form id="form3" name="form3" method="post" action="<%=request.getcontextpath()%>/importfilebean_servlet" enctype="multipart/form-data"> <div class="row"> <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12" style="height:80px;"> <input id="excel1" name="excel1" width="100%" type="text" style="width:90%;height: 34px;" > </div> </div> <div class="row"> <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12 text-center"> <input type="button" id="saveimport" class="btn form-control btn-success dialogbuttom-btn" value="导入" onclick="dotoolbar(this.id);"/> </div> </div> <input type="hidden" id="active2" name="active" /> </form> </div> </div> </div> </div> </body> <script type="text/javascript"> $(document).ready(function(){ initdialog();//初始化对话框 initfilebox(); loadgrid(); }); /**工具栏按钮调用方法,传入按钮的id @id 当前按钮点击事件 **/ function dotoolbar(itoolbar){ //点击按钮打开上传附件弹窗 if (itoolbar == 'importtjxx'){ $('#importinfodialog').dialog('settitle', '导入'); $('#importinfodialog').dialog("open"); } //点击按钮打开上传附件弹窗 if (itoolbar == 'deletetjxx'){ layer.confirm('删除后无法恢复,您是否确认删除?', { btn: ['确定','取消'] }, function(){ deletetjxx(); }, function(){ }); } //上传体检excel文件 if (itoolbar == 'saveimport'){ var excel1 = $('#excel1').filebox('getvalue') var excelsuffix=excel1.substring(excel1.lastindexof("."),excel1.length); if($('#excel1').filebox('getvalue') == ''){ layer.alert('请选择上传文件'); return; } if(excelsuffix!=".xls" && excelsuffix!=".xlsx"){ layer.alert('只能导入excel类型的文件!'); return; } $("#active2").val("importexaminfo"); showshade();//打开遮罩层 $('#form3').submit(); } } //删除ajax function deletetjxx(){ $.ajax({ type:"post", url:'<%=request.getcontextpath()%>/importfilebean_svl', data:"active=deletetjxx", datatype:"json", success: function(datas){ if(datas[0].msg == '删除成功'){ layer.msg(datas[0].msg); loadgrid(); }else{ layer.alert(datas[0].msg); } } }); } //遮罩层 function showshade(){ $('#maskfont2').html('导入中,请稍候...'); $('#divpagemask4').show(); } //上传按钮初始化 function initfilebox(){ $('#excel1').filebox({ buttontext: '选择文件', buttonalign: 'right' }); } /**加载 dialog控件**/ function initdialog(){ $('#importinfodialog').dialog({ width: 360,//宽度设置 height: 200,//高度设置 modal:true, closed: true, cache: false, draggable:false,//是否可移动dialog框设置 //打开事件 onopen:function(data){}, //读取事件 onload:function(data){}, //关闭事件 onclose:function(data){ $('#form3').form('clear'); } }); } //加载datagrid主页面信息 function loadgrid(){ $('#list').datagrid({ url: '<%=request.getcontextpath()%>/importfilebean_svl', queryparams: {"active":"querylist"}, loadmsg : "信息加载中请稍后!",//载入时信息 nowrap: false,//当数据长度超出列宽时将会自动截取 showfooter:true, rownumbers: true, animate:true, striped : true,//隔行变色 pagesize : 10,//每页记录数 singleselect : true,//单选模式 pagenumber : 20,//当前页码 pagination:true, fit:true, fitcolumns: true,//设置边距 columns:[[ {field:'编号',title:'序号',width:fillsize(0.2)}, {field:'体检者',title:'姓名',width:fillsize(0.2)}, {field:'体检日期',title:'体检日期',width:fillsize(0.2)}, {field:'体检机构',title:'体检机构',width:fillsize(0.2)}, {field:'体检结果',title:'体检结果',width:fillsize(0.2)} ]], onclickrow:function(rowindex, rowdata){ row=rowdata; }, onloadsuccess: function(data){ ikeycode=''; }, onloaderror:function(none){ } }); } //表单提交方法 $('#form3').form({ //定位到servlet位置的url url:'<%=request.getcontextpath()%>/importfilebean_servlet', //当点击事件后触发的事件 onsubmit: function(data){ }, //当点击事件并成功提交后触发的事件 success:function(data){ var json = eval("("+data+")"); if(json[0].msg=="导入完成"){ $('#divpagemask4').hide(); $('#importinfodialog').dialog("close"); layer.msg(json[0].msg); loadgrid(); }else if(json[0].msg=="未找到sheet1"){ layer.alert("工作表名称不符"); }else{ layer.alert(json[0].msg); } } }); </script> </html>
servlet代码如下:
servlet中拦截前台的importexaminfo导入请求,在调用bean层中的导入逻辑处理方法!
package or.og.jxldemo; import java.io.ioexception; import java.sql.sqlexception; import java.util.vector; import javax.servlet.servletconfig; import javax.servlet.servletexception; import javax.servlet.http.httpservlet; import javax.servlet.http.httpservletrequest; import javax.servlet.http.httpservletresponse; import com.jspsmart.upload.smartupload; import com.jspsmart.upload.smartuploadexception; import com.pantech.base.common.exception.wrongsqlexception; import com.pantech.base.common.tools.jsonutil; import com.pantech.base.common.tools.mytools; import net.sf.json.jsonarray; public class importfilebean_servlet extends httpservlet { private static final long serialversionuid = 1l; protected void doget(httpservletrequest request, httpservletresponse response) throws servletexception, ioexception { dopost(request, response); } protected void dopost(httpservletrequest request, httpservletresponse response) throws servletexception, ioexception { request.setcharacterencoding("utf-8");//request编码类型 response.setcontenttype("text/html;charset=utf-8");//reponse类型统一 vector vector=new vector(); jsonarray jsonarray = new jsonarray(); vector jsonv = null;//返回结果集 jsonarray jal = null;//返回json对象 importfilebean bean = new importfilebean(request); servletconfig sc = this.getservletconfig(); smartupload mysmartupload = new smartupload("utf-8"); mysmartupload.initialize(sc, request, response);//获取request及response对象 try { mysmartupload.upload(); } catch (smartuploadexception exception1) { // todo 自动生成 catch 块 exception1.printstacktrace(); } getparameters(request, bean,mysmartupload);//初始化参数 string active = mytools.strfiltr(mysmartupload.getrequest().getparameter("active"));//获取前台提交的操作类型 //导入信息 if(active.equalsignorecase("importexaminfo")){ try { bean.importexaminfo(mysmartupload);//调用bean层中逻辑方法 jsonarray = jsonutil.addjsonparams(jsonarray, "msg", bean.getmsg());//转换json数据格式 response.getwriter().write(jsonarray.tostring());//返回服务器端响应 } catch (sqlexception e) { // todo 自动生成 catch 块 e.printstacktrace(); } catch (smartuploadexception e) { // todo 自动生成 catch 块 e.printstacktrace(); } catch (wrongsqlexception e) { // todo 自动生成 catch 块 e.printstacktrace(); } } } //获得页面参数 public void getparameters(httpservletrequest request,importfilebean bean,smartupload mysmartupload){ } }
servlet中拦截前台的查询datadrig数据网格请求,在调用bean层中的查询方法!
package or.og.jxldemo; import java.io.ioexception; import java.sql.sqlexception; import java.util.vector; import javax.servlet.servletexception; import javax.servlet.http.httpservlet; import javax.servlet.http.httpservletrequest; import javax.servlet.http.httpservletresponse; import com.jspsmart.upload.smartuploadexception; import com.pantech.base.common.exception.wrongsqlexception; import com.pantech.base.common.tools.jsonutil; import com.pantech.base.common.tools.mytools; import com.pantech.base.common.tools.tracelog; import net.sf.json.jsonarray; public class importfilebean_svl extends httpservlet { protected void doget(httpservletrequest request, httpservletresponse response) throws servletexception, ioexception { dopost(request, response); } /** * @see httpservlet#dopost(httpservletrequest request, httpservletresponse response) */ protected void dopost(httpservletrequest request, httpservletresponse response) throws servletexception, ioexception { //设置字符编码为utf-8 request.setcharacterencoding("utf-8"); response.setcontenttype("text/html;charset=utf-8"); string active = mytools.strfiltr(request.getparameter("active"));// 拿取前台的active值 int pagenum = mytools.parseint(request.getparameter("page")); //获得页面page参数 分页 int pagesize = mytools.parseint(request.getparameter("rows")); //获得页面rows参数 分页 vector jsonv = null;//返回结果集 jsonarray jal = null;//返回json对象 importfilebean bean = new importfilebean(request); this.getformdata(request, bean); //获取submit提交时的参数(ajax适用) system.out.println("active:--"+active); //查询全部信息 if("querylist".equalsignorecase(active)){ try { try { jsonv=bean.querylist(pagenum,pagesize); } catch (wrongsqlexception e) { // todo auto-generated catch block e.printstacktrace(); } jal = (jsonarray)jsonv.get(2); response.getwriter().write("{\"total\":" + mytools.strfiltr(jsonv.get(0)) + ",\"rows\":" + jal.tostring() + "}"); tracelog.trace("response: "+jal.tostring()); } catch (sqlexception e) { e.printstacktrace(); } } //删除全部信息 if("deletetjxx".equalsignorecase(active)) { try { bean.deletetjxx(); //返回操作信息 jal=jsonutil.addjsonparams(jal, "msg", bean.getmsg()); response.getwriter().write(jal.tostring()); } catch (wrongsqlexception e) { // todo auto-generated catch block e.printstacktrace(); } catch (sqlexception e) { // todo auto-generated catch block e.printstacktrace(); } } } /** * 从界面没获取参数 * @date * @author:yeq * @param request * @param majorsetbean */ private void getformdata(httpservletrequest request, importfilebean bean){ } }
bean代码:
注:bean中的导入方法中分别对.xsl和.xsls两种表格数据文件进行不同处理!
package or.og.jxldemo; import java.io.file; import java.io.fileinputstream; import java.io.ioexception; import java.io.inputstream; import java.sql.sqlexception; import java.text.parseexception; import java.text.simpledateformat; import java.util.date; import java.util.vector; import javax.servlet.servletexception; import javax.servlet.http.httpservletrequest; import org.apache.poi.hssf.usermodel.hssfsheet; import org.apache.poi.hssf.usermodel.hssfworkbook; import org.apache.poi.ss.usermodel.cell; import org.apache.poi.ss.usermodel.row; import org.apache.poi.xssf.usermodel.xssfsheet; import org.apache.poi.xssf.usermodel.xssfworkbook; import com.jspsmart.upload.smartfile; import com.jspsmart.upload.smartfiles; import com.jspsmart.upload.smartupload; import com.jspsmart.upload.smartuploadexception; import com.pantech.base.common.db.dbsource; import com.pantech.base.common.exception.wrongsqlexception; import com.pantech.base.common.tools.mytools; public class importfilebean { private httpservletrequest request; private dbsource db; private string msg;//提示消息 /** * <p>title: </p> * <p>description: </p> * @param request */ //获取对象 public importfilebean(httpservletrequest request) { this.request = request; this.db = new dbsource(request); } //查询全部信息 public vector querylist(int pagenum,int pagesize)throws wrongsqlexception,sqlexception{ vector vec = null; string sql="select [编号],[体检者],convert(nvarchar(19),[体检日期],21)as 体检日期,[体检机构],[体检结果] " + "from [v_个人档案_体检记录] "; vec = db.getconttexjonsarr(sql, pagenum, pagesize); return vec; } //删除全部信息 public void deletetjxx()throws wrongsqlexception,sqlexception{ string sql="delete from [v_个人档案_体检记录] "; if(db.executeinsertorupdate(sql)) { this.setmsg("删除成功"); }else { this.setmsg("删除失败"); } } /** * @title: saveimpxls * @description: 导入体检信息 * @author lupengfei * @date 2016-7-19 */ @suppresswarnings("unchecked") public void importexaminfo(smartupload mysmartupload) throws sqlexception, servletexception, ioexception, smartuploadexception, wrongsqlexception{ dbsource db = new dbsource(request); string sql=""; string sqlmx=""; vector vec = null; // 结果集 string tempsheet="";//sheet名 string tempsoin="";//第1列 string tempsoin2=""; string templine="";//第3列 int sheetnum=0;//sheet计数 string bh="";//编号 string tjzxm="";//体检者姓名 string tjrq="";//体检日期 string tjjgmc="";//体检机构名称 string tjjg="";//体检结果 string path = "c:/temp/upload"; file f1 = new file(path); //当文件夹不存在时创建 if (!f1.exists()) { f1.mkdirs(); } //workbook workbook = null; hssfworkbook workbook = null; xssfworkbook workbook2 = null; vector vectormx=new vector(); smartfiles files = mysmartupload.getfiles(); //获取文件 smartfile file= null; //判断 if(files.getcount() > 0){ file = files.getfile(0); if(file.getsize()<=0){ msg = "文件内容为空,请确认!"; } file.saveas(path +"/"+file.getfilename()); } path=path +"/"+file.getfilename(); string filename=file.getfilename(); system.out.println("file=:"+file.getfilename()); file file1=new file(path); try { inputstream is = new fileinputstream(file1); if (filename.substring(filename.indexof(".")+1,filename.length()).equals("xls")) { workbook = new hssfworkbook(is); system.out.println(workbook.getnumberofsheets()); for(int k=0;k<workbook.getnumberofsheets();k++){ //控制循环几个sheet hssfsheet sheet = workbook.getsheetat(k); //获取sheet(k)的数据对象 tempsheet=workbook.getsheetname(k);//获取sheet名 int firstrowindex = sheet.getfirstrownum(); int lastrowindex = sheet.getlastrownum(); int rsrows=lastrowindex; if(lastrowindex==0){ }else{ if("sheet1".equalsignorecase(tempsheet.trim().tolowercase())){//对工作表名称进行判断 system.out.println("sheet:"+tempsheet+" rows="+rsrows); sheetnum++; int locbh=-1;//编号 int loctjzxm=-1;//体检者姓名 int loctjrq=-1;//体检日期 int loctjjgmc=-1;//体检机构名称 int loctjjg=-1;//体检结果 row currentrow = sheet.getrow(0);// 当前行 int firstcolumnindex = currentrow.getfirstcellnum(); // 首列 int lastcolumnindex = currentrow.getlastcellnum();// 最后一列 //对头标题进行判断记录下标 for (int columnindex = firstcolumnindex; columnindex < lastcolumnindex; columnindex++) { cell currentcell = currentrow.getcell(columnindex);// 当前单元格 tempsoin = this.getcellvalue(currentcell, true);// 当前单元格的值 if(tempsoin.equalsignorecase("编号")){ locbh=columnindex; }else if(tempsoin.equalsignorecase("体检者")){ loctjzxm=columnindex; }else if(tempsoin.equalsignorecase("体检日期")){ loctjrq=columnindex; }else if(tempsoin.equalsignorecase("体检机构")){ loctjjgmc=columnindex; }else if(tempsoin.equalsignorecase("体检结果")){ loctjjg=columnindex; } } for (int i = 1; i <= rsrows; i++) {//从第2行遍历excel文件 currentrow = sheet.getrow(i);// 当前行 if (currentrow == null) { }else{ firstcolumnindex = currentrow.getfirstcellnum(); // 首列 lastcolumnindex = currentrow.getlastcellnum();// 最后一列 for (int columnindex =firstcolumnindex; columnindex < lastcolumnindex; columnindex++) { cell currentcell = currentrow.getcell(columnindex);// 当前单元格 tempsoin = this.getcellvalue(currentcell, true);// 当前单元格的值 if(tempsoin.equalsignorecase("")){ continue; }else{ if(locbh==-1){ bh=""; //编号列 }else{ if(locbh==columnindex){ bh=tempsoin.trim(); } } if(loctjzxm==-1){ tjzxm=""; //体检者 }else{ if(loctjzxm==columnindex){ tjzxm=tempsoin.trim(); } } if(loctjrq==-1){ tjrq=""; //体检日期列 }else{ if(loctjrq==columnindex){ tjrq=tempsoin.trim(); tjrq=convertdate(tjrq);//转换时间类型 } } if(loctjjgmc==-1){ tjjgmc=""; //体检机构 }else{ if(loctjjgmc==columnindex){ tjjgmc=tempsoin.trim(); } } if(loctjjg==-1){ tjjg=""; //体检结果列 }else{ if(loctjjg==columnindex){ tjjg=tempsoin.trim(); } } } } sqlmx=" insert into v_个人档案_体检记录 ([编号],[体检者],[体检日期],[体检机构],[体检结果]) values (" + "'"+mytools.fixsql(bh)+"'," +//编号 "'"+mytools.fixsql(tjzxm)+"'," +//体检者姓名 "'"+mytools.fixsql(tjrq)+"'," +//体检日期 "'"+mytools.fixsql(tjjgmc)+"'," +//体检机构名称 "'"+mytools.fixsql(tjjg)+"') " ;//体检结果 vectormx.add(sqlmx); } } } } } } else if (filename.substring(filename.indexof(".")+1,filename.length()).equals("xlsx")) { workbook2 = new xssfworkbook(is); system.out.println(workbook2.getnumberofsheets()); for(int k=0;k<workbook2.getnumberofsheets();k++){ xssfsheet sheet = workbook2.getsheetat(k); //获取sheet(k)的数据对象 tempsheet=workbook2.getsheetname(k);//获取sheet名 int firstrowindex = sheet.getfirstrownum(); int lastrowindex = sheet.getlastrownum()+1; int rsrows=lastrowindex; if(lastrowindex==1){ }else{ system.out.println("sheet:"+tempsheet+" rows="+rsrows); if("sheet1".equalsignorecase(tempsheet.trim().tolowercase())){ sheetnum++; int locbh=-1;//编号 int loctjzxm=-1;//体检者姓名 int loctjrq=-1;//体检日期 int loctjjgmc=-1;//体检机构名称 int loctjjg=-1;//体检结果 row currentrow = sheet.getrow(0);// 当前行 int firstcolumnindex = currentrow.getfirstcellnum(); // 首列 int lastcolumnindex = currentrow.getlastcellnum();// 最后一列 for (int columnindex = firstcolumnindex; columnindex < lastcolumnindex; columnindex++) { cell currentcell = currentrow.getcell(columnindex);// 当前单元格 tempsoin = this.getcellvalue(currentcell, true);// 当前单元格的值 if(tempsoin.equalsignorecase("编号")){ locbh=columnindex; }else if(tempsoin.equalsignorecase("体检者")){ loctjzxm=columnindex; }else if(tempsoin.equalsignorecase("体检日期")){ loctjrq=columnindex; }else if(tempsoin.equalsignorecase("体检机构")){ loctjjgmc=columnindex; }else if(tempsoin.equalsignorecase("体检结果")){ loctjjg=columnindex; } } for (int i = 1; i < rsrows; i++) {//从第2行遍历excel文件 currentrow = sheet.getrow(i);// 当前行 if (currentrow == null) { }else{ firstcolumnindex = currentrow.getfirstcellnum(); // 首列 lastcolumnindex = currentrow.getlastcellnum();// 最后一列 for (int columnindex = firstcolumnindex; columnindex < lastcolumnindex; columnindex++) { cell currentcell = currentrow.getcell(columnindex);// 当前单元格 tempsoin = this.getcellvalue(currentcell, true);// 当前单元格的值 if(tempsoin.equalsignorecase("")){ continue; }else{ if(locbh==-1){ bh=""; //编号列 }else{ if(locbh==columnindex){ bh=tempsoin.trim(); } } if(loctjzxm==-1){ tjzxm=""; //体检者 }else{ if(loctjzxm==columnindex){ tjzxm=tempsoin.trim(); } } if(loctjrq==-1){ tjrq=""; //体检日期列 }else{ if(loctjrq==columnindex){ tjrq=tempsoin.trim(); tjrq=convertdate(tjrq);//转换时间类型 } } if(loctjjgmc==-1){ tjjgmc=""; //体检机构 }else{ if(loctjjgmc==columnindex){ tjjgmc=tempsoin.trim(); } } if(loctjjg==-1){ tjjg=""; //体检结果列 }else{ if(loctjjg==columnindex){ tjjg=tempsoin.trim(); } } } } sqlmx=" insert into v_个人档案_体检记录 ([编号],[体检者],[体检日期],[体检机构],[体检结果]) values (" + "'"+mytools.fixsql(bh)+"'," +//编号 "'"+mytools.fixsql(tjzxm)+"'," +//体检者姓名 "'"+mytools.fixsql(tjrq)+"'," +//体检日期 "'"+mytools.fixsql(tjjgmc)+"'," +//体检机构名称 "'"+mytools.fixsql(tjjg)+"') " ;//体检结果 } vectormx.add(sqlmx); } } } } } if(db.executeinsertorupdatetransaction(vectormx)){ this.msg="导入完成"; }else{ this.msg="导入失败"; } if(sheetnum==0){ this.msg="未找到sheet1"; } }catch (exception e) { e.printstacktrace(); } finally { //workbook.close(); } } /** * 取单元格的值 * @param cell 单元格对象 * @param treatasstr 为true时,当做文本来取值 (取到的是文本,不会把“1”取成“1.0”) * @return */ private string getcellvalue(cell cell, boolean treatasstr) { if (cell == null) { return ""; } if (treatasstr) { // 虽然excel中设置的都是文本,但是数字文本还被读错,如“1”取成“1.0” // 加上下面这句,临时把它当做文本来读取 cell.setcelltype(cell.cell_type_string); } if (cell.getcelltype() == cell.cell_type_boolean) { return string.valueof(cell.getbooleancellvalue()); } else if (cell.getcelltype() == cell.cell_type_numeric) { return string.valueof(cell.getnumericcellvalue()); }else { return string.valueof(cell.getstringcellvalue()); } } // 转换日期 public static string convertdate(string s) throws parseexception{ if (s == null || "".equals(s)) { return ""; } // 将excel读取日期时遇到数字 转化为日期 // excel 的一个有趣之处就是,当您试图将数字转换为日期时,程序会假定该数字是一个序列号, // 代表自 1900 年 1 月 1 日起所发生的天数。自 1900 年 1 月 1 日 算起的第 39331 天就是 2007 年 9 月 6 日 string rtn = "1900-01-01"; simpledateformat format = new simpledateformat("yyyy-mm-dd"); date date1 = new date(); date1 = format.parse("1900-01-01"); long i1 = date1.gettime(); // 这里要减去2,(long.parselong(s)-2) 不然日期会提前2天,具体原因不清楚, // 估计和java计时是从1970-01-01开始有关 // 而excel里面的计算是从1900-01-01开始 i1 = i1 / 1000 + ((long.parselong(s) - 2) * 24 * 3600); date1.settime(i1 * 1000); rtn = format.format(date1); return rtn; } public string getmsg() { return msg; } public void setmsg(string msg) { msg = msg; } }
至此java操作jxl批量导入数据成功,本人只是写了一个简单的小案例可自行扩展功能及所需表格格式