您的位置:首页 > 数据库

上传,解析Excel文件并保存数据到数据库

2017-03-20 14:35 1131 查看
web框架:spring+hibernate+jQuery

HTML端代码:

<div class="file-up-content">

<table id="fileDiv" class="table">

<tr>

<td colspan="3"> 请采用excel文件格式。 <input type="hidden" id="isHaveAttFile" name="isHaveAttFile"

value="0" /> <input type="hidden" id="resultfileurls"

name="resultfileurls" value="${report.resultinfoListString}" />

</td>

</tr>

<tr>

<td valign="top" colspan="3">

<table>

<tr id="fileList">

<c:if test="${!empty rinfoList }">

<c:forEach items="${rinfoList}" var="item" varStatus="var">

<tr id="p_${item.id }">

<td><a id="p_${item.id }_a" href="<c:url value='${item.localurl}'/>" target="_blank">${item.localurl }</a>

<a href="javascript:;" onclick="removePic('${item.id}', '${item.localurl }','removefile', '${novkjcx.id }');">x</a>

</td>

</tr>

</c:forEach>

</c:if>

</tr>

</table>

<span id="uploadfileButton" style="color:#6699CC; cursor:pointer " title="点击继续添加!">添加附件</span>

<span id="resultfileurlsShowMessage" style="color: red"></span>

</td>

<td>  <br /></td>

</tr>

</table>

</div>

对应的js代码部分:

<!-- 文件上传弹窗开始 -->

<div id="fileText" class="easyui-window" modal="true" closed="true"

title="  上传" iconCls="icon-save"

style="width:500px;height:240px;padding:5px;background-color:#fafafa;">

<div class="easyui-layout" fit="true">

<div region="center" border="false"

style="padding:10px;background:#fff;border:1px solid #ccc;">

<form method="post" encoding="multipart/form-data">

<div id="fileQueue"></div>

浏览:<input type="file" id="uploadify" name="uploadify" /><br /> 解释:

<textarea id="uploadDescribe" name="uploadDescribe" cols="45"

rows="3"></textarea>

</form>

</div>

<div region="south" border="false"

style="text-align:right;height:30px;line-height:30px;">

<a class="easyui-linkbutton" iconCls="icon-ok"

href="javascript:void(0)"

onClick="$('#uploadify').uploadifyUpload();">上传</a> <a

class="easyui-linkbutton" iconCls="icon-cancel"

href="javascript:void(0)" onClick="$('#fileText').window('close');">取消</a>

</div>

</div>

</div>

<!-- 文件上传弹窗结束 -->

<script>

$(function() {

$("#uploadfileButton").click(function() {

uploadType = 4;

$("#uploadDescribe").val("");

uploadFileExt = "*.*";

try {

$('#uploadify').uploadifySettings("fileDesc", uploadFileExt);

$('#uploadify').uploadifySettings("fileExt", uploadFileExt);

} catch (err) {

}

upload();

});

});

</script>

<script>

var basePath = "";

var pdfpicPath = "/novelty/images/simplefile/pdf.png";

var reportid = $("#reportid").val();

var isUploadFileShow = false;

var uploadType, uploadFileExt;

$(function() {

$("#uploadfileButton").click(function() {

uploadType = 4;

$("#uploadDescribe").val("");

uploadFileExt = "*.*";

try {

$('#uploadify').uploadifySettings("fileDesc", uploadFileExt);

$('#uploadify').uploadifySettings("fileExt", uploadFileExt);

} catch (err) {

}

upload();

});

});

function upload() {

$('#fileText').window('open');

//window.opener.$("#fileText");

if (!isUploadFileShow) {

$('#uploadify')

.uploadify(

{

// 以下参数均是可选

'uploader' : '<c:url value="/js/jquery-uploadify/flash/uploadify.swf"/>', // 指定上传控件的主体文件,默认‘uploader.swf’

'script' : '<c:url value="/fileserver/upload"/>', // 指定服务器端上传处理文件,默认‘upload.php’

'method' : 'post',

'scriptData' : {

'attid' : $("#attid").val(),

'describe' : $("#uploadDescribe").val()

},

'cancelImg' : '<c:url value="/js/jquery-uploadify/images/cancel.png"/>', // 指定取消上传的图片,默认‘cancel.png’

'fileDataName' : 'uploadify',

'auto' : false, // 选定文件后是否自动上传,默认false

'folder' : '/imageService/compressIMG', // 要上传到的服务器路径,默认‘/’

'muti' : false, // 是否允许同时上传多文件,默认false

'queueID' : 'fileQueue',

//'queueSizeLimit' : 4,
// 队列中同时存在的文件个数限制

'fileDesc' : uploadFileExt, // 出现在上传对话框中的文件类型描述

'fileExt' : uploadFileExt, // 控制可上传文件的扩展名,启用本项时需同时声明fileDesc

'sizeLimit' : 104857600, // 控制上传文件的大小,单位byte(10MB)

//'simUploadLimit' : 5,
// 多文件上传时,同时上传文件数目限制

//'buttonText' : 'Browser',
// 按钮上的文字

//'displayData' : 'percentage',
// 有speed和percentage两种,一个显示速度,一个显示完成百分比

'onSelect' : function() {

$('#uploadify').uploadifySettings(

'scriptData',

{

'rnd' : Math.random(),

'attid' : $("#attid").val(),

'describe' : $("#uploadDescribe").val()

});

if (uploadType == 1) {

$('#uploadify').uploadifySettings(

'script',

'<c:url value="/fileserver/upload?uploadType=1"/>&attid='

+ $("#attid").val());

} else {

$('#uploadify').uploadifySettings(

'script',

'<c:url value="/fileserver/upload?uploadType=4"/>&attid='

+ $("#attid").val());

}

},

'onComplete' : function(event, queueID,

fileObj, response, data) {

var obj = $.parseJSON(response);

if (obj.flag == "true") {

ymPrompt.alert("上传成功!" + obj.message,

300,

185,

"信息提示",

function(data) {

if (data == "ok") {

$('#fileText').window('close');

$("#fileList")

.append(

" <tr id=\"p_" + obj.id + "\"><td><a id=\"p_" + obj.id+"_a\"" +" href=\"" + basePath + obj.url + "\" target=\"_blank\">"

+ obj.url

+ "</a> <a href=\"javascript:;\" onclick=\"removePic('"

+ obj.id

+ "', '"

+ obj.url

+ "','removefile', '"

+ reportid

+ "');\">x</a></td></tr>");

}

});

} else {

ymPrompt.alert("上传失败!" + obj.message,

300, 185, "信息提示");

}

}

});

isUploadFileShow = true;

}

}

function removePic(id, url, what, reportid) {

ymPrompt.confirmInfo('确认删除?', 300, 185, '信息提示', function(data1) {

if (data1 == 'ok') {

$.ajax({

type : "post",

data : {

id : id,

url : url,

what : what,

reportid : reportid

},

url : '<c:url value="/embed/fileDelete.htm"/>?act=delete'

+ '&d=' + Math.random(),

dataType : "json",

beforeSend : function(XMLHttpRequest) {

},

success : function(data) {

if (data.flag == "true") {

if ('removecover' == what) {

var urls = $("#imageURL").val();

var href = $("#p_" + id + "_a").attr("href");

href = href.substr(14);

//urls=urls.replace(href,'').replace(";;",";");

$("#imageURL").val(urls);

} else if ('removefile' == what) {

var urls = $("#resultfileurls").val();

var href = $("#p_" + id + "_a").attr("href");

href = href.substr(14);

//urls=urls.replace(href,'').replace(";;",";");

$("#resultfileurls").val(urls);

}

$("#p_" + data.id).remove();

} else {

// ymPrompt.alert("删除失败!" + data.message, 300, 185, "信息提示");

}

},

complete : function(XMLHttpRequest, textStatus) {

},

error : function(data) {

alert(data);

}

});

} else {

return false;

}

});

}

</script>

后端controller程序处理代码:

protected void formSubmit(HttpServletRequest request,

HttpServletResponse response, Object command, Errors errors,

PmUserSession userSession, PageSession pageSession)

throws Exception {

String attid=request.getParameter("attid"); //attid为对应Excel文件的UUID号

if(WebUtils.isNotNull(attid)){

List<AAA> rinfoList=dao.find(" from AAA obj where obj.attid='"+attid+"' and del=0"); //AAA为数据库中存文件路径的表名用hibernate映射之后的名称

if(rinfoList.size()>0){

File f=new File(rinfoList.get(0).getLocalurl());

ImportTerm i=new ImportTerm();

i.importTerm(f, dao,attid);

response.sendRedirect(request.getContextPath() + "/embed/datasetElement.htm?id="+request.getParameter("dataset"));

}

}

}

调用ImportTerm类的方法:

package cn.nsl.data;

import java.io.File;

import java.util.List;

import org.apache.poi.ss.usermodel.Row;

import org.apache.poi.ss.usermodel.Sheet;

import org.apache.poi.ss.usermodel.Workbook;

import org.apache.poi.ss.usermodel.WorkbookFactory;

import org.springframework.context.ApplicationContext;

import org.springframework.context.support.ClassPathXmlApplicationContext;

import cn.nsl.domain.glob.DataSet;

import cn.nsl.domain.glob.DataSetElement;

import cn.nsl.domain.glob.Elements;

import cn.nsl.web.Application;

import com.jbetter.spring.orm.ICommonDao;

public class ImportTerm extends ImportExcel {

public void importTerm(File f,ICommonDao dao,String attid){

try {

Workbook wb;

wb = WorkbookFactory.create(f);

Sheet sheet = wb.getSheet("Sheet1");

importTermSheet(sheet,dao,dataset,attid);

} catch (Exception e) {

// TODO Auto-generated catch block

log.error(e);

e.printStackTrace();

}

}

void importTermSheet(Sheet sheet,ICommonDao dao,DataSet dataset,String attid) throws Exception{

int rowEnd = Math.max(100, sheet.getLastRowNum());

for(int i=1;i<=rowEnd;i++){

importTermProd(sheet.getRow(i),dao,dataset,attid);

}

}

void importTermProd(Row r,ICommonDao dao,DataSet dataset,String attid) throws Exception{

String code=getString(r, 0);

String cnname = getString(r, 1);

String name = getString(r, 2);

String frequency = getString(r, 3);

String limiting = getString(r, 4);

String multiJATS = getString(r, 5);

String remarks = getString(r, 6);

biaoming c = new biaoming();

c.setFrequency(frequency);

c.setLimiting(limiting);

c.setMultiJATS(multiJATS);

c.setRemarks(remarks);

c.setAttid(attid);

dao.save(c);

}

public static void main(String []args){

System.setProperty("file.encoding", "UTF-8");

ApplicationContext apx = new ClassPathXmlApplicationContext("applicationContext-hibernate.xml");

dao = (ICommonDao) apx.getBean("commonDao");

ImportTerm i = new ImportTerm();

i.importTerm(new File("D://term.xlsx"),dao,null,"dd");

}

}

到此Excel上传解析入库完成。方法多种多样,熟练一种就可以了。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息