前段时间做一个小项目,为了同时存储多条数据,其中有一个功能是解析Excel并把其中的数据存入对应数据库中。花了两天时间,不过一天多是因为用了"upload"关键字作为URL从而导致总报同一个错,最后在同学的帮助下顺利解决,下面我把自己用"POI"解析的方法总结出来供大家参考(我用的是SpingMVC和hibernate框架)。

1.web.xml中的配置文件

web.xml中的配置文件就按照这种方式写,只需要把"application.xml"换成你的配置文件名即可

 <!--文件上传对应的配置文件-->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:application.xml</param-value>
</context-param>

2.application.xml的配置文件(固定写发)

在这个配置文件中你还可以规定上传文件的格式以及大小等多种属性限制

 <!-- 定义文件上传解析器 -->
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
</bean>

3.文件上传的前端HTML

注意:1.enctype="multipart/form-data" 必须写,封装表单

2.method="post",提交方式必须为"post"提交

3.action="${text}/uploadfile", "uploadfile"切记不要写成"upload",否则你找到世界末日也不会找到哪里有问题(本人因为这个折腾了一天多时间)。

 <form name="fileupload" enctype="multipart/form-data" action="${text}/uploadfile" method="post">
<p style="font-size:16px;">请选择正确的excel文件上传</p>
<input id="txt" class="input" type="text" disabled="disabled" value="文件域" name="txt">
<input class="liulan" type="button" onclick="file.click()" size="30" value="上传文件" onmousemove="file.style.pixelLeft=event.x-60;file.style.pixelTop=this.offsetTop;">
<input id="file1" class="files" type="file" hidefocus="" size="1" style="height:26px;" name="file" onchange="txt.value=this.value">
<br/><input type="button" onclick="checkSuffix();" value="提交上传" style="height:26px;width:100px">
<p style="color:red;">支持的excel格式为:xls、xlsx、xlsb、xlsm、xlst!</p>
</form>

4.验证上传文件的格式

 //用于验证文件扩展名的正则表达式
function checkSuffix(){
var name = document.getElementById("txt").value;
var strRegex = "(.xls|.xlsx|.xlsb|.xlsm|.xlst)$";
var re=new RegExp(strRegex);
if (re.test(name.toLowerCase())){
alert("上传成功");
document.fileupload.submit();
} else{
alert("文件名不合法");
}
}

5.dao层的接口和实现类

 package com.gxxy.team1.yyd.dao;

 public interface IFileUploadDao {
public void save(Object o);
}
 package com.gxxy.team1.yyd.dao.impl;

 import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository; import com.gxxy.team1.yyd.dao.IFileUploadDao;
@Repository
public class FileUploadDaoImpl implements IFileUploadDao {
@Autowired
private SessionFactory sessionFactory;
private Session getSession() {
Session session = sessionFactory.getCurrentSession();
return session;
}
@Override
public void save(Object o) { getSession().save(o);
} }

6.service层的接口和实现类

 package com.gxxy.team1.yyd.service;

 import java.util.List;

 public interface IFileUploadService {
public List<String[]> readExcel(String path);
public void save(Object o);
}
 package com.gxxy.team1.yyd.service.impl;

 import java.io.File;
import java.io.FileInputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List; import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.DateUtil;
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.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; import com.gxxy.team1.yyd.dao.IFileUploadDao;
import com.gxxy.team1.yyd.service.IFileUploadService;
@Service
public class FileUploadServiceImpl implements IFileUploadService {
@Autowired
private IFileUploadDao fileDao;
@Override
public List<String[]> readExcel(String path) {
SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");
List<String[]> list = null;
try {
//同时支持Excel 2003、2007
File excelFile = new File(path); //创建文件对象
FileInputStream is = new FileInputStream(excelFile); //文件流
Workbook workbook = WorkbookFactory.create(is); //这种方式 Excel 2003/2007/2010 都是可以处理的
int sheetCount = workbook.getNumberOfSheets(); //Sheet的数量
//存储数据容器
list = new ArrayList<String[]>();
//遍历每个Sheet
for (int s = 0; s < sheetCount; s++) {
Sheet sheet = workbook.getSheetAt(s);
int rowCount = sheet.getPhysicalNumberOfRows(); //获取总行数
//遍历每一行
for (int r = 0; r < rowCount; r++) {
Row row = sheet.getRow(r);
int cellCount = row.getPhysicalNumberOfCells(); //获取总列数
//用来存储每行数据的容器
String[] model = new String[cellCount-1];
//遍历每一列
for (int c = 0; c < cellCount; c++) {
Cell cell = row.getCell(c);
int cellType = cell.getCellType(); if(c == 0) continue;//第一列ID为标志列,不解析 String cellValue = null;
switch(cellType) {
case Cell.CELL_TYPE_STRING: //文本
cellValue = cell.getStringCellValue();
//model[c-1] = cellValue;
break;
case Cell.CELL_TYPE_NUMERIC: //数字、日期
if(DateUtil.isCellDateFormatted(cell)) {
cellValue = fmt.format(cell.getDateCellValue()); //日期型
//model[c-1] = cellValue;
}
else { cellValue = String.valueOf(cell.getNumericCellValue()); //数字
//model[c-1] = cellValue;
}
break;
case Cell.CELL_TYPE_BOOLEAN: //布尔型
cellValue = String.valueOf(cell.getBooleanCellValue());
break;
case Cell.CELL_TYPE_BLANK: //空白
cellValue = cell.getStringCellValue();
break;
case Cell.CELL_TYPE_ERROR: //错误
cellValue = "错误";
break;
case Cell.CELL_TYPE_FORMULA: //公式
cellValue = "错误";
break;
default:
cellValue = "错误"; }
System.out.print(cellValue + " "); model[c-1] = cellValue;
}
//model放入list容器中
list.add(model);
System.out.println();
}
}
is.close();
}
catch (Exception e) {
e.printStackTrace();
} return list;
}
@Override
public void save(Object o) {
fileDao.save(o);
}
}

7.controller层实现

 //文件上传方法
@RequestMapping("/uploadfile")
public String upload(@RequestParam(value = "file", required = false) MultipartFile file, HttpServletRequest request, ModelMap model,Model mod) throws Exception {
String path = request.getSession().getServletContext().getRealPath("upload");
System.out.println("文件路径:"+path);
String originalFilename = file.getOriginalFilename();
String type = file.getContentType();
//originalFilename = UUID.randomUUID().toString()+originalFilename;
System.out.println("目标文件名称:"+originalFilename+",目标文件类型:"+type);
File targetFile = new File(path,originalFilename );
if (!targetFile.getParentFile().exists()) {
targetFile.getParentFile().mkdirs();
}else if (!targetFile.exists()) {
targetFile.mkdirs();
}
// 获得上传文件的文件扩展名
String subname = originalFilename.substring(originalFilename.lastIndexOf(".")+1);
System.out.println("文件的扩展名:"+subname); try {
file.transferTo(targetFile);
} catch (Exception e) {
e.printStackTrace();
}
FileUploadServiceImpl fileUp = new FileUploadServiceImpl();
String rootpath = path + File.separator + originalFilename;
List<String[]> excellist = fileUp.readExcel(rootpath);
int len = excellist.size();
System.out.println("集合的长度为:"+len);
for (int i = 0; i < len; i++) {
String[] fields = excellist.get(i);
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
String sampleNo = fields[0]; Double valueOf = Double.valueOf(fields[1]);
int sampleType = valueOf.intValue(); //double转int String createTime = fields[2];
Date createTime1 = format.parse(createTime);
String name = fields[3];
String pId = fields[4];
String hospitalName = fields[5];
String cellPhone = fields[6];
Sample sample = new Sample(sampleNo, sampleType, createTime1, name, pId);
Patient patient = new Patient(hospitalName, cellPhone);
fileService.save(sample);
fileService.save(patient);
}
//model.addAttribute("fileUrl", request.getContextPath()+"/upload/"+originalFilename); String username = (String) request.getSession().getAttribute("username");
List<List<Menu>> power = powerService.power(username);
mod.addAttribute("list", power);
return "redirect:/ yyd";
}

以上这7个部分就是我实现解析excel文件并存入数据库的全部代码。

解析Excel文件并把数据存入数据库的更多相关文章

  1. Springboot 上传CSV文件并将数据存入数据库

    .xml文件依赖配置 <!--csv依赖 --> <dependency> <groupId>org.apache.commons</groupId> ...

  2. 解析excel文件并将数据导入到数据库中

    今天领导给安排了一个临时工作,让我将一个excel里面的数据解析后放入数据库中,经过一个下午的努力成功完成,现在将代码献上,希望对大家有所帮助 一.需要导入的jar 1.commons-collect ...

  3. 使用joomla通过CSV文件上传数据存入数据库并使用JavaScript验证码是否符合规则

    1,实现效果截图 2,A.php上传CSV文件表单 2-1:html结构使用jqeury.form.min.js表单框架异步提交 <div class="uploadFile bord ...

  4. Python解析excel文件并存入sqlite数据库

    最近由于工作上的需求 需要使用Python解析excel文件并存入sqlite 就此做个总结 功能:1.数据库设计 建立数据库2.Python解析excel文件3.Python读取文件名并解析4.将解 ...

  5. vue下载和上传excle数据文件,解析excel文件数据并存在数据库中

    下载: VUE: window.open("xxxx/downloadOldTaskDataFile.do_", "_blank"); JAVA: /** * ...

  6. Django中从本地上传excel文件并将数据存储到数据库

    Django中从本地上传excel文件并将数据存储到数据库 一.前端界面 <div class="page-container"> <form action=&q ...

  7. .Net读取Excel文件时丢失数据的问题 (转载)

    相信很多人都试过通过OleDB读取Excel文件,这种方法效率十分高,只是有一点会让人十分头痛,就是当一列中既有混合型数据,又有纯数据时,往往容易丢失数据. 百度过后,改连接字符串 “HDR=YES; ...

  8. Java通过jxl解析Excel文件入库,及日期格式处理方式 (附源代码)

    JAVA可以利用jxl简单快速的读取文件的内容,但是由于版本限制,只能读取97-03  xls格式的Excel. 本文是项目中用到的一个实例,先通过上传xls文件(包含日期),再通过jxl进行读取上传 ...

  9. 自动化测试如何解析excel文件?

    前言 自动化测试中我们存放数据无非是使用文件或者数据库,那么文件可以是csv,xlsx,xml,甚至是txt文件,通常excel文件往往是我们的首选,无论是编写测试用例还是存放测试数据,excel都是 ...

随机推荐

  1. (转)Uploadify 3.2 参数属性、事件、方法函数详解

    转自http://blog.sina.com.cn/s/blog_5079086b0101fkmh.html Hallelujah博客 一.属性 属性名称 默认值 说明 auto true 设置为tr ...

  2. wcf、web api、webservicer 之间的区别

    名次注解 SOAP 简单对象访问协议(SOAP)是一种轻量的.简单的.基于 XML 的协议,是交换数据的一种协议规范,是一种轻量的.简单的.基于XML(标准通用标记语言下的一个子集)的协议,它被设计成 ...

  3. Windows:将cmd命令行添加到右键中方法

    win10中将命令行cmd添加到右键的方法 Windows cmd 右键 win10 命令行 最近在学python,所以会用到很多库文件,但是有的库文件需要下载whl文件再通过cmd进行安装,所以每次 ...

  4. Angular2开发拙见——组件规划篇

    本文集中讲讲笔者目前使用ng2来开发项目时对其组件的使用的个人的一些拙劣的经验. 先简单讲讲从ng1到ng2框架下组件的职责与地位: ng1中的一大特色--指令,分为属性型.标签型.css类型和注释型 ...

  5. iOS开发寻找最近公共view

    新技能 #pragma mark --寻找最近公共view + (NSArray *)superViews:(UIView *)view{ if (view==nil) { return @[]; } ...

  6. 将ROS中的/sensor_msgs/NavSatFix数据导入google earth显示轨迹

    将ros中的gps_msg数据导入google earth显示轨迹 [TOC] 1. 获取GPS数据 将ros中发布的gps topic输出到文本中 rostopic echo -p /gpsData ...

  7. P2物理引擎中文文档

    P2物理引擎中文文档地址:https://github.com/schteppe/p2.js/wiki/Chinese-wiki-%E4%B8%AD%E6%96%87%E7%BB%B4%E5%9F%B ...

  8. 静态链表实现(A-B)+(B-A)【代码】

    -----------------------------------------------第一次发代码,写在前面------------------------------------------ ...

  9. Android -- 从源码带你从EventBus2.0飚到EventBus3.0(一)

    1,最近看了不少的面试题,不管是百度.网易.阿里的面试题,都会问到EventBus源码和RxJava源码,而自己只是在项目中使用过,却没有去用心的了解它底层是怎么实现的,所以今天就和大家一起来学习学习 ...

  10. 如何了解您的微软认证情况和MIC ID