版权声明:本文为博主原创文章,未经博主允许不得转载。
前提:项目中需要把EXCEL数据批量导入oracle中两张表中。如是用到了poi技术。分别导入poi-3.11-beta2.jar和poi-ooxml-schemas-3.9.jar这两个包。EXCEL数据如下
第一步:修改spring框架配置文件。 springmvc-servlet.xml加上:
<!-- 文件上传 -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver" p:defaultEncoding="utf-8" />
第一步:添加页面jsp。view_user_batchadd.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<%
String importMsg="";
if(request.getSession().getAttribute("msg")!=null){
importMsg=request.getSession().getAttribute("msg").toString();
}
request.getSession().setAttribute("msg", "");
%>
<head>
<title>批量导入用户</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript" src="<%=request.getContextPath()%>/view/js/jquery.js"></script>
<body>
<form action="<%=request.getContextPath()%>/manager/index/batchimport" method="post" enctype="multipart/form-data" name="batchAdd" οnsubmit="return check();">
<div style="margin: 30px;"><input id="excel_file" type="file" name="filename" accept="xls" size="50"/>
<div><input id="excel_file" type="file" name="filename" size="50"/>
<input id="excel_button" type="submit" value="导入Excel"/></div>
<font id="importMsg" color="red"><%=importMsg%></font><input type="hidden"/>
</form>
</body>
<script type="text/javascript">
function check() {
var excel_file = $("#excel_file").val();
if (excel_file == "" || excel_file.length == 0) {
alert("请选择文件路径!");
return false;
} else {
return true;
}
}
$(document).ready(function () {
var msg="";
if($("#importMsg").text()!=null){
msg=$("#importMsg").text();
}
if(msg!=""){
alert(msg);
}
});
</script>
</html>第三步:填写控制器:UserLoginController.Java
/**
* 2014-8-30 下午2:52:49
* TODO 用户登录 Controller
*
*/
@Controller
@RequestMapping("/index")
public class UserLoginController {
private Log log = LogFactory.getLog(UserLoginController.class);
@Autowired
private UserLoginService userLoginService;
@Autowired
private UserInfoService userInfoService;
@RequestMapping(value = "/batchimport", method = RequestMethod.POST)
public ModelAndView batchimport(@RequestParam("filename") MultipartFile file,HttpServletRequest request,HttpServletResponse response) throws Exception{
log.info("UserLoginController ..batchimport() start");
//判断文件名是否为空
if(file==null) return null;
//获取文件名
String name=file.getOriginalFilename();
//判断文件大小、即名称
long size=file.getSize();
if(name==null || ("").equals(name) && size==0) return null;
try {
//把文件转换成字节流形式
InputStream in = file.getInputStream();
int i=userLoginService.batchImport(name,file);
int j=userInfoService.batchImport(name,file);
if(i>0 && j>0){
String Msg ="批量导入EXCEL成功!";
request.getSession().setAttribute("msg",Msg);
}else{
String Msg ="批量导入EXCEL失败!";
request.getSession().setAttribute("msg",Msg);
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
注:我这个Controller的方法里面处理了两个接口实现类。我这里就写一个
第三步:实现类:UserLoginServiceImpl.java
public int batchImport(String name,MultipartFile file) throws Exception {
//处理EXCEL
ReadExcel readExcel=new ReadExcel();
//获得解析excel方法
List<User> userList=readExcel.getExcelInfo(name,file);
//把excel信息添加到数据库中
List<UserLogin> LoginList=new ArrayList<UserLogin>();
for(User user:userList){
LoginList.add(user.getUserLogin());
}
return userLoginDao.saveBatch(LoginList);//添加登录信息
}
第四步:处理EXCEL类:ReadExcel.java
public class ReadExcel {
//总行数
private int totalRows = 0;
//总条数
private int totalCells = 0;
//错误信息接收器
private String errorMsg;
//构造方法
public ReadExcel(){}
//得到总行数
public int getTotalRows() { return totalRows;}
//得到总列数
public int getTotalCells() { return totalCells;}
public String getErrorInfo() { return errorMsg; }
/**
* 描述:验证EXCEL文件
* @param filePath
* @return
*/
public boolean validateExcel(String filePath){
if (filePath == null || !(WDWUtil.isExcel2003(filePath) || WDWUtil.isExcel2007(filePath))){
errorMsg = "文件名不是excel格式";
return false;
}
return true;
}
/**描述 :读EXCEL文件
* @param fielName
* @return
*/
public List<User> getExcelInfo(String fileName,MultipartFile Mfile){
//把spring文件上传的MultipartFile转换成File
CommonsMultipartFile cf= (CommonsMultipartFile)Mfile;
DiskFileItem fi = (DiskFileItem)cf.getFileItem();
File file = fi.getStoreLocation();
List<User> userList=new ArrayList<User>();
InputStream is = null;
try{
//验证文件名是否合格
if(!validateExcel(fileName)){
return null;
}
//判断文件时2003版本还是2007版本
boolean isExcel2003 = true;
if(WDWUtil.isExcel2007(fileName)){
isExcel2003 = false;
}
is = new FileInputStream(file);
userList=getExcelInfo(is, isExcel2003);
is.close();
}catch(Exception e){
e.printStackTrace();
}
finally{
if(is !=null)
{
try{
is.close();
}catch(IOException e){
is = null;
e.printStackTrace();
}
}
}
return userList;
}
/**
* 此方法两个参数InputStream是字节流。isExcel2003是excel是2003还是2007版本
* @param is
* @param isExcel2003
* @return
* @throws IOException
*/
public List<User> getExcelInfo(InputStream is,boolean isExcel2003){
List<User> userList=null;
try{
/** 根据版本选择创建Workbook的方式 */
Workbook wb = null;
//当excel是2003时
if(isExcel2003){
wb = new HSSFWorkbook(is);
}
else{
wb = new XSSFWorkbook(is);
}
userList=readExcelValue(wb);
}
catch (IOException e) {
e.printStackTrace();
}
return userList;
}
/**
* 读取Excel里面的信息
* @param wb
* @return
*/
private List<User> readExcelValue(Workbook wb){
//得到第一个shell
Sheet sheet=wb.getSheetAt(0);
//得到Excel的行数
this.totalRows=sheet.getPhysicalNumberOfRows();
//得到Excel的列数(前提是有行数)
if(totalRows>=1 && sheet.getRow(0) != null){
this.totalCells=sheet.getRow(0).getPhysicalNumberOfCells();
}
List<User> userList=new ArrayList<User>();
User user; //用户bean(组成:UserInfo+UserLogin)
UserInfo userInfo; //用户基本信息bean
UserLogin userLogin; //用户登录bean
//循环Excel行数,从第二行开始。标题不入库
for(int r=1;r<totalRows;r++)
{
Row row = sheet.getRow(r);
if (row == null) continue;
user=new User();
userInfo=new UserInfo();
userLogin=new UserLogin();
//循环Excel的列
for(int c = 0; c <this.totalCells; c++)
{
Cell cell = row.getCell(c);
if (null != cell)
{
//第一列
if(c==0){
//获得第一列<用户名>,放到到用户基本信息bean中。
userInfo.setUserName(cell.getStringCellValue());
}
//获得第二列<手机号>,放到到用户登录bean中。作为登录账号及密码
else if(c==1){
/**
* 处理:使用POI读excel文件,当遇到特殊格式的字串,比如“13612345678”,等等,
* 这样的本来是一个字符串,但是POI在读的时候总是以数值型识别,由此,这样的电话号码读出来后总是1.3XXX+E4
*/
DecimalFormat df = new DecimalFormat("#");
String cellValue=df.format(cell.getNumericCellValue());
userLogin.setAccount(cellValue);
userLogin.setPwd(cellValue);
}
//第三列目前不入库,只是展示即可
//第四列<用户地址>,放到到用户基本信息bean中。
else if(c==3){
userInfo.setCompanyAdd(cell.getStringCellValue());
}
}
}
//添加其他值,入库时需要
userLogin.setUserId(Utils.getzId());//存放用户ID
userLogin.setInsertTime(Utils.getshortDate());//注册时间
userLogin.setUserRole("2"); //默认导入的用户都为供应商级别
userInfo.setUserInfoid(Utils.getzId());//存放用户ID
userInfo.setUserId(userLogin.getUserId());//基本信息的用户ID
user.setUserInfo(userInfo);
user.setUserLogin(userLogin);
userList.add(user);
}
return userList;
}
}
/**
* @描述:工具类
* 检验是否是EXCEL文件
*/
class WDWUtil
{
// @描述:是否是2003的excel,返回true是2003
public static boolean isExcel2003(String filePath) {
return filePath.matches("^.+\\.(?i)(xls)$");
}
//@描述:是否是2007的excel,返回true是2007
public static boolean isExcel2007(String filePath) {
return filePath.matches("^.+\\.(?i)(xlsx)$");
}
}
<script>window._bd_share_config = { "common": { "bdSnsKey": {}, "bdText": "", "bdMini": "1", "bdMiniList": false, "bdPic": "", "bdStyle": "0", "bdSize": "16" }, "share": {} }; with (document) 0[(getElementsByTagName('head')[0] || body).appendChild(createElement('script')).src = 'http://bdimg.share.baidu.com/static/api/js/share.js?v=89860593.js?cdnversion=' + ~(-new Date() / 36e5)];</script>
rel="stylesheet" href="http://static.blog.csdn.net/css/blog_detail.css" />
<script type="text/javascript" id="bdshare_js" data="type=tools&uid=1536434" src="http://bdimg.share.baidu.com/static/js/bds_s_v2.js?cdnversion=407358"></script><script type="text/javascript">document.getElementById("bdshell_js").src = "http://bdimg.share.baidu.com/static/js/shell_v2.js?cdnversion=" + Math.ceil(new Date()/3600000)</script>
顶
-
1
踩
-
0
<script type="text/javascript">function btndigga() { $(".tracking-ad[data-mod='popu_222'] a").click(); } function btnburya() { $(".tracking-ad[data-mod='popu_223'] a").click(); }</script>
我的同类文章
- •Spring AOP 的关键概念2012-11-13
<script type="text/javascript">$(function () { GetCategoryArticles('1285946', 'zlxdream815','foot','41086995'); });</script>
<script language="javascript" type="text/javascript">$(function(){ $.get("/zlxdream815/svc/GetSuggestContent/41086995",function(data){ $("#suggest").html(data); }); });</script> rel="stylesheet" href="http://static.blog.csdn.net/css/replace.css" />
<script src="http://csdnimg.cn/jobreco/job_reco.js" type="text/javascript"></script> <script type="text/javascript">csdn.position.showEdu({ sourceType: "blog", searchType: "detail", searchKey: "41086995", username: "", recordcount: "5", containerId: "adCollege" //容器DIV的id。 });</script>
<script type="text/javascript">$(function () { setTimeout(function () { var searchtitletags = '把EXCEL用程序导入到ORACLE中(SpringMVC+MyBatis)' + ',' + $("#tags").html(); searchService({ index: 'blog', query: searchtitletags, from: 5, size: 5, appendTo: '#res', url: 'recommend', his: 2, client: "blog_cf_enhance", tmpl: '
猜你在找
#{ title }
' }); }, 500); });</script>
<script src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
width="728" height="90" frameborder="0" marginwidth="0" marginheight="0" vspace="0" hspace="0" allowtransparency="true" scrolling="no" allowfullscreen="true" οnlοad="var i=this.id,s=window.google_iframe_oncopy,H=s&&s.handlers,h=H&&H[i],w=this.contentWindow,d;try{d=w.document}catch(e){}if(h&&d&&(!d.body||!d.body.firstChild)){if(h.call){setTimeout(h,0)}else if(h.match){try{h=s.upd(h,i)}catch(e){}w.location.replace(h)}}" id="aswift_0" name="aswift_0" style="left:0;position:absolute;top:0;"><script>(adsbygoogle=window.adsbygoogle || []).push({});</script>
<script type="text/javascript">$(function () { $("#ad_frm_0").height("90px"); setTimeout(function(){ $("#ad_frm_2").height("200px"); },1000); });</script>
核心技术类目
全部主题
Hadoop
AWS
移动游戏
Java
Android
iOS
Swift
智能硬件
Docker
OpenStack
VPN
Spark
ERP
IE10
Eclipse
CRM
JavaScript
数据库
Ubuntu
NFC
WAP
jQuery
BI
HTML5
Spring
Apache
.NET
API
HTML
SDK
IIS
Fedora
XML
LBS
Unity
Splashtop
UML
components
Windows Mobile
Rails
QEMU
KDE
Cassandra
CloudStack
FTC
coremail
OPhone
CouchBase
云计算
iOS6
Rackspace
Web App
SpringSide
Maemo
Compuware
大数据
aptech
Perl
Tornado
Ruby
Hibernate
ThinkPHP
HBase
Pure
Solr
Angular
Cloud Foundry
Redis
Scala
Django
Bootstrap
<script language="javascript" type="text/javascript">$(function(){ setTimeout(function(){ $.get("/zlxdream815/svc/GetTagContent",function(data){ $(".tag_list").html(data).show(); }); }); },500);</script>
<script type="text/javascript">$(function(){ setTimeout(function(){ $(".comment_body:contains('回复')").each(function(index,item){ var u=$(this).text().split(':')[0].toString().replace("回复","") var thisComment=$(this); if(u) { $.getJSON("https://passport.csdn.net/get/nick?callback=?", {users: u}, function(a) { if(a!=null&&a.data!=null&&a.data.length>0) { nick=a.data[0].n; if(u!=nick) { thisComment.text(thisComment.text().replace(u,nick)); } } }); } }); },200); setTimeout(function(){ $(".math").each(function(index,value){$(this).find("span").last().css("color","#fff"); }) },5000); setTimeout(function(){ $(".math").each(function(index,value){$(this).find("span").last().css("color","#fff"); }) },10000); setTimeout(function(){ $(".math").each(function(index,value){$(this).find("span").last().css("color","#fff"); }) },15000); setTimeout(function(){ $("a img[src='http://js.tongji.linezing.com/stats.gif']").parent().css({"position":"absolute","left":"50%"}); },300); }); function loginbox(){ var $logpop=$("#pop_win"); $logpop.html(' src="https://passport.csdn.net/account/loginbox?service=http://static.blog.csdn.net/callback.htm" frameborder="0" height="600" width="400" scrolling="no">'); $('#popup_mask').css({ opacity: 0.5, width: $( document ).width() + 'px', height: $( document ).height() + 'px' }); $('#popup_mask').css("display","block"); $logpop.css( { top: ($( window ).height() - $logpop.height())/ 2 + $( window ).scrollTop() + 'px', left:($( window ).width() - $logpop.width())/ 2 } ); setTimeout( function () { $logpop.show(); $logpop.css( { opacity: 1 } ); }, 200 ); $('#popup_mask').unbind("click"); $('#popup_mask').bind("click", function(){ $('#popup_mask').hide(); var $clopop = $("#pop_win"); $("#common_ask_div_sc").css("display","none"); $clopop.css( { opacity: 0 } ); setTimeout( function () { $clopop.hide(); }, 350 ); return false; }); }</script> <script language="javascript" type="text/javascript" src="http://ads.csdn.net/js/async_new.js"></script>
- 个人资料
-
- 访问:59662次
- 积分:960
- 等级:
- 排名:千里之外
- 原创:36篇
- 转载:6篇
- 译文:1篇
- 评论:5条
- 文章搜索
-
<script type="text/javascript">$(function () { $("#btnSubmit").click(function () { search(); }); $("#frmSearch").submit(function () { search(); return false; }); function search() { var url = "http://so.csdn.net/so/search/s.do?q=" + encodeURIComponent($("#inputSearch").val()) + "&u=" + username + "&t=blog"; window.location.href = url; } });</script>
- 文章分类
- 文章存档
-
- 阅读排行
- 【mysql】mysql的内连接和外连接小例子(10372)
- maven:把本地jar包导入到maven仓库中(6805)
- JSP 截取字符串 { EL表达式截取字符串}(4082)
- jdk为tomcat配置ssl证书及安装——(安装失败后分析)(3696)
- Timer和spring的Quartz两种定时器的区别。(3598)
- 把EXCEL用程序导入到ORACLE中(SpringMVC+MyBatis)(3338)
- 【java】jdom解析xml文件(2808)
- 在jsp中用<s:if test />比较两个变量(2380)
- 把数据库数据导入出来成EXCEL(SpringMVC+Mybatis+mysql+easyUI)(2257)
- {jsp 循环显示list内容}(1990)
- 评论排行
- 推荐文章
- 最新评论
- Timer和spring的Quartz两种定时器的区别。
Coder_ChanBin:看了一下基本表达的意思就是可以互相转换?顺便能否说一下,这两个运行效率和所占用的资源有什么区别吗 0...
- 把EXCEL用程序导入到ORACLE中(SpringMVC+MyBatis)
sunzhuang:大神,请问 您的源码还在吗?跪求参考。。。。
- 【mysql】mysql的内连接和外连接小例子
xiaoshu220:简单易懂
- Spring基础xfire报:报 Error initializing XFireServlet.
jch330483:万分感谢!一个困扰了我们好几天的问题解决了!
- maven:把本地jar包导入到maven仓库中
zhougang1008:。。。。
<script type="text/javascript" src="http://c.csdnimg.cn/rabbit/cnick/cnick.js"></script><script type="text/javascript" src="http://static.blog.csdn.net/scripts/newblog.min.js"></script><script type="text/javascript" src="http://medal.blog.csdn.net/showblogmedal.ashx?blogid=1367091"></script><script type="text/javascript" src="http://static.blog.csdn.net/scripts/JavaScript1.js"></script> rel="stylesheet" type="text/css" href="//csdnimg.cn/pubfooter/css/pub_footer_2014.css" />
<script id="noticeScript" type="text/javascript" btnid="header_notice_num" wrapid="note1" count="5" subcount="5" src="//csdnimg.cn/rabbit/notev2/js/notify.js?9d86d94"></script> <script type="text/javascript" src="http://passport.csdn.net/content/loginbox/login.js"></script><script type="text/javascript">document.write("");</script><script type="text/javascript" src="http://www.csdn.net/ui/scripts/Csdn/counter.js"></script><script type="text/javascript" charset="UTF-8" src="http://message.csdn.net/msg.popup.js"></script><script type="text/javascript" src="http://ad.csdn.net/scripts/ad-blog.js"></script><script type="text/javascript">$(function () { function __get_code_toolbar(snippet_id) { return $("" + ""); } $("[code_snippet_id]").each(function () { __s_id = $(this).attr("code_snippet_id"); if (__s_id != null && __s_id != "" && __s_id != 0 && parseInt(__s_id) > 70020) { __code_tool = __get_code_toolbar(__s_id); $(this).prev().find(".tools").append(__code_tool); } }); $(".bar").show(); });</script>
<script id="csdn-toolbar-id" btnid="header_notice_num" wrapid="note1" count="5" subcount="5" type="text/javascript" src="http://c.csdnimg.cn/public/common/toolbar/js/toolbar.js"></script>
href="http://c.csdnimg.cn/comm_ask/css/ask_float_block.css" type="text/css" rel="stylesheet" /> <script language="JavaScript" type="text/javascript" src="http://c.csdnimg.cn/comm_ask/js/libs/wmd.js"></script> <script language="JavaScript" type="text/javascript" src="http://c.csdnimg.cn/comm_ask/js/libs/showdown.js"></script> <script language="JavaScript" type="text/javascript" src="http://c.csdnimg.cn/comm_ask/js/libs/prettify.js"></script> <script language="JavaScript" type="text/javascript" src="http://c.csdnimg.cn/comm_ask/js/apps/ask_float_block.js"></script>
rel="stylesheet" type="text/css" media="screen" href="http://ask.csdn.net/assets/ask_float_fonts_css-6b30a53970eb5c3a2a045e3df585b475.css" />
1楼 sunzhuang 2016-06-11 15:41发表 [回复]-
-
大神,请问 您的源码还在吗?跪求参考。。。。