专注收集记录技术开发学习笔记、技术难点、解决方案
网站信息搜索 >> 请输入关键词:
您当前的位置: 首页 > 数据库

多构件上传excel文档,解析后存入mysql数据库

发布时间:2010-05-20 14:01:29 文章来源:www.iduyao.cn 采编人员:星星草
多部件上传excel文档,解析后存入mysql数据库

说明:此处使用的是java的ssm框架

           jsp的界面

           mysql批量数据插入

多部件上传,配置文件中的定义

<bean id="multipartResolver"

class="org.springframework.web.multipart.commons.CommonsMultipartResolver">

<property name="defaultEncoding">

<value>UTF-8</value>

</property>

<!-- 定义最大上传文件的大小,自定义,可不用限定-->

<property name="maxUploadSize">

<value>31457280</value>

</property>

</bean>

 

1.jsp部分,多部件方式文件异步上传multipart 

【多部件上传满足三条件:form表单,type=“file” enctype="multipart/form-data"】

<form  id="uploadForm"  enctype="multipart/form-data">

<input file="file" name="file" id="file_sc" type="file" class="btn btn-primary btn-sm">

<input class="btn btn-primary btn-sm" onclick="uploadExcelFile()" value="提交"/>

</form>

 

2.js部分 包括对导入的内容检查 异步上传,可对上传后返回结果处理

function uploadExcelFile() {

var file=$("#file_sc").val();  

if (file == "") {

alert("请选择要导入的excel文件!!!"); 

}else {

var formData =new FormData($("#uploadForm")[0]);

$.ajax({  

         url: urlRootContext+"/knowledgebase.do?method=addKBContent",  

         type: 'POST',  

         data:formData,

         cache: false,  

     contentType: false,

         processData: false,

         dataType : "json",

         success: function (data) {  

        var returnDataTemp=data.returnData;

if (returnDataTemp=="0") {

            alert("导入数据失败!");    

} else if(returnDataTemp=="1"){

        alert("导入数据成功!"); 

}             

         },  

         error: function (data) {

             alert("导入数据失败,请检查网络稍后再试!"); 

         }  

    });  

}

 

3.controller部分

//导入运维数据处理后存储到
@RequestMapping(params = "method=addKBContent")
public void addKBContent(HttpServletRequest request, HttpServletResponse response,@RequestParam(value = "file", required = false) MultipartFile file) {


String fileName = file.getOriginalFilename();
         System.out.println("--------" + fileName + "-------");
         JSONObject jsonObj=new JSONObject();
         try {
      //创建上传路径,excel内容读取完全之后,将文件删除/iop/WebRoot/WEB-INF/page/knowledgebase/kbcontent.jsp
String fileFolderPath=request.getSession().getServletContext().getRealPath("/WEB-INF/page/knowledgebase/Excel/");
String filePath=fileFolderPath+fileName;
File uploadFile=new  File(filePath);
         // 正式上传文件
         file.transferTo(uploadFile);
//导入已存在的Excel文件,获得只读的工作薄对象  。此处将excel中获取的数据封装到list集合中 根据excel中数据自己定义对象
List<KnowledgeBaseContent> list = new ArrayList<KnowledgeBaseContent>();
FileInputStream fileIn = new FileInputStream(filePath);
//根据指定的文件输入流导入Excel从而产生Workbook对象
Workbook wb0 = new HSSFWorkbook(fileIn);
//获取Excel文档中的第一个表单
Sheet sht0 = wb0.getSheetAt(0);
int count=1;
//对Sheet中的每一行进行迭代
for (Row r : sht0) {   
//如果当前行的行号(从0开始)未达到2(第三行)则从新循环
if (r.getRowNum()<1){
continue;
}  
//创建实体类
KnowledgeBaseContent kbcontent=new KnowledgeBaseContent();
//取出当前行第1个单元格数据,并封装在info实体stuName属性上
kbcontent.setKbcontentId(kbcontentId);
count++;
list.add(kbcontent);
   }
fileIn.close();
//读取完毕,将文件删除
File fileDelete =new File(filePath);
if (fileDelete.exists()) {
fileDelete.delete();
}

//此处,定义每次插入100条,你可根据数据量自己定义
int EACH_SIZE=100;
//分批次插入,100行为界限
int countTime=(list.size())/EACH_SIZE;
//int maxSize=(list.size())%EACH_SIZE;
int maxSize=list.size();
if (countTime<1) {
kbContentService.addKBContentList(list);
}else{
//多次插入内容时 分批次插入数据
for (int i = 0; i < countTime; i++) {
int endSize=(i+1)*EACH_SIZE-1;
kbContentService.addKBContentList(list.subList(i*EACH_SIZE,endSize));
}
kbContentService.addKBContentList(list.subList(countTime*EACH_SIZE,maxSize));
}

} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
jsonObj.accumulate("returnData","0");
}         
//批量添加数据
         jsonObj.accumulate("returnData", "1");
PrintWriteOut.printWirter(response, jsonObj);
}

 

4.mybatis中的数据插入

<!-- 添加表格中数据  list集合-->

<insert id="addKBContentList" parameterType="java.util.List">

    insert IGNORE into iop_kbcontent

    (   

        kbcontent_id                                         

    )

    values

    <foreach collection="list" item="item" index= "index" separator =",">

    (

        #{item.kbcontentId}

    )

    </foreach>

</insert>

 

友情提示:
信息收集于互联网,如果您发现错误或造成侵权,请及时通知本站更正或删除,具体联系方式见页面底部联系我们,谢谢。

其他相似内容:

热门推荐: