读取ppt并存入数据库_Java解析Excel文件并把数据存入数据库

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

1.web.xml中的配置文件

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

org.springframework.web.context.ContextLoaderListener

contextConfigLocation

classpath:application.xml

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

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

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

3.文件上传的前端HTML

注意:

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

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

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

请选择正确的excel文件上传

支持的excel格式为:xls、xlsx、xlsb、xlsm、xlst!

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 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 readExcel(String path) {

SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");

List 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();

//遍历每个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 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> power = powerService.power(username);

mod.addAttribute("list", power);

return "redirect:/ yyd";

}

以上这7个部分就是我实现解析excel文件并存入数据库的全部代码。希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/441195.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

两台虚拟服务器如何级联,[教程] 利用open vswitch建立vxlan隧道实现不同主机上的虚拟交换机级联...

写在开头在某些环境下&#xff0c;需要实现两台物理机中的openvswitch交换机级联&#xff0c;以实现两台交换机中的设备互相通讯&#xff0c;这里使用vxlan隧道技术&#xff0c;将数据包封装在UDP中&#xff0c;通过以太网实现数据包传输。VXLAN是一种大二层的虚拟技术&#xf…

【POJ - 3041】Asteroids (二分图,最小点覆盖)

题干&#xff1a; Bessie wants to navigate her spaceship through a dangerous asteroid field in the shape of an N x N grid (1 < N < 500). The grid contains K asteroids (1 < K < 10,000), which are conveniently located at the lattice points of the…

华为虚拟服务器lanip地址,2018软考网络工程师《华为基础实验》十九配置路由器为DHCPServer...

原标题&#xff1a;2018软考网络工程师《华为基础实验》十九配置路由器为DHCPServer实验要求:在R1上使能DHCP 功能。创建三个全局地址池&#xff0c;用于为三个不同部门的PC分配IP 地址。配置地址池的相关属性。在R1的接口下配置基于全局地址池的服务方式&#xff0c;实现DHCP …

电脑重启bootmgr_电脑系统启动:显示0xc0000428怎么办

错误代码&#xff1a;0xc0000428 一般都是驱动问题&#xff0c;只需要找到报错的路径驱动程序&#xff0c;删除再重启就基本上可以解决了。制作一个U盘启动&#xff0c;进入PE&#xff0c;然后删除”\Windoiws\System32\drivers\DsArk64.sys“文件&#xff0c;再重启就可以了。…

【 POJ - 2033 】Alphacode (dp,有坑)

题干&#xff1a; Alice and Bob need to send secret messages to each other and are discussing ways to encode their messages: Alice: "Lets just use a very simple code: Well assign A the code word 1, B will be 2, and so on down to Z being assigned 26.&…

两组的数据平均值合并_不要进入数据陷进

学习统计让我们不再被一些数据迷惑进入数据陷进&#xff08;例如平均工资&#xff09;从而做出正确的决策。描述性统计分析包括数据的分布、集中、波动的测度指标。平均值&#xff1a;一组数据的加和除以数据的个数&#xff08;容易随极端值变化&#xff09; 中位数&#xff1a…

【POJ - 3342】Party at Hali-Bula(树形dp,最大独立集,是否有唯一解)

题干&#xff1a; Dear Contestant, Im going to have a party at my villa at Hali-Bula to celebrate my retirement from BCM. I wish I could invite all my co-workers, but imagine how an employee can enjoy a party when he finds his boss among the guests! So, I…

安川西格玛7驱动器手册_什么是伺服驱动器?选型的原则有哪些?

头条号私信回复1&#xff0c;获取海量免费学习资源&#xff0c;内容包括自动化电气工程师必备的软件、电子书、视频教程等题图&#xff1a;伺服驱动器来源&#xff1a;百度图片什么是伺服驱动器&#xff1f;该如何选型&#xff1f;有哪些主流品牌&#xff1f;你想知道的全在这里…

java猜数游戏图形界面_Java做一个猜数的小游戏

Author &#xff1a; By Runsen效果展现猜数字游戏是一个简单&#xff0c;有趣的小游戏。游戏者通过输入一个指定区间的数字&#xff0c;与系统产生的随机数进行对比&#xff0c;然后输出相应的结果。游戏运行时产生一个0&#xff0d;10之间的随机整数&#xff0c;要求用户从控…

【CodeForces - 266C】Below the Diagonal (递归,子问题,贪心模拟)

题干&#xff1a; You are given a square matrix consisting of n rows and n columns. We assume that the rows are numbered from 1 to n from top to bottom and the columns are numbered from 1to n from left to right. Some cells (n - 1 cells in total) of the t…

python 0o_Python 中的比较:is 与 ==

在 Python 中会用到对象之间比较&#xff0c;可以用 &#xff0c;也可以用 is 。但是它们的区别是什么呢&#xff1f;is 比较的是两个实例对象是不是完全相同&#xff0c;它们是不是同一个对象&#xff0c;占用的内存地址是否相同。莱布尼茨说过&#xff1a;“世界上没有两片完…

python中long类型_浅谈python 四种数值类型(int,long,float,complex)

Python支持四种不同的数值类型,包括int(整数)long(长整数)float(浮点实际值)complex (复数),本文章向码农介绍python 四种数值类型,需要的朋友可以参考一下。 数字数据类型存储数值。他们是不可改变的数据类型,这意味着改变数字数据类型的结果,在一个新分配的对象的值。 N…

【CodeForces - 264A】Escape from Stones (模拟,卡精度的处理)

题干&#xff1a; Squirrel Liss lived in a forest peacefully, but unexpected trouble happens. Stones fall from a mountain. Initially Squirrel Liss occupies an interval [0, 1]. Next, nstones will fall and Liss will escape from the stones. The stones are nu…

python开发mbus程序_Python pywmbus包_程序模块 - PyPI - Python中文网

#WIP WM总线在Python中的实现本项目实施了无线m-bus标准的部分内容&#xff0c;定义见din en 13757-1及以下。目前&#xff0c;只支持未加密的短帧(即ci 0x7a)。欢迎拉取请求。##安装###点pip install pywmbus###手动git clone https://github.com/jalmeroth/pywmbus.gitcd pyw…

【CodeForces - 266B 】Queue at the School (模拟)

题干&#xff1a; During the break the schoolchildren, boys and girls, formed a queue of n people in the canteen. Initially the children stood in the order they entered the canteen. However, after a while the boys started feeling awkward for standing in fr…

查看git当前tag_Git - git tag - 查看当前分支 tag 版本说明

索引&#xff1a;参看代码 GitHub&#xff1a;一、示例&#xff1a;1 git tag -l -n二、说明:1."tag" 部分tag 代表的是标签动作,可以带参数 ,也可以不带参数,带上不同的参数可以实现标签的 新建/删除/查询/验证 等功能.2."-l" 部分-l 注意是字母"L&q…

【CodeForces - 270A】Fancy Fence (几何,思维,水题)

题干&#xff1a; Emuskald needs a fence around his farm, but he is too lazy to build it himself. So he purchased a fence-building robot. He wants the fence to be a regular polygon. The robot builds the fence along a single path, but it can only make fenc…

判断集合相等_数学启蒙的每个关键阶段之集合分类

本文我们将分享数学启蒙学什么&#xff1f;用几个字简单的归纳为集合、数、量、形、时间、空间。我们接下来会讲感知集合和分类&#xff0c;数概念&#xff0c;量的概念&#xff0c;形状包含平面图形和立体图形&#xff0c;空间方位和时间的初步概念。 家长们可以发现幼儿数学启…

【CodeForces - 271B 】Prime Matrix (素数,预处理打表,思维)

题干&#xff1a; Youve got an n  m matrix. The matrix consists of integers. In one move, you can apply a single transformation to the matrix: choose an arbitrary element of the matrix and increase it by 1. Each element can be increased an arbitrary numb…

【CodeForces - 270C】Magical Boxes (思维,进制,有坑)

题干&#xff1a; Emuskald is a well-known illusionist. One of his trademark tricks involves a set of magical boxes. The essence of the trick is in packing the boxes inside other boxes. From the top view each magical box looks like a square with side leng…