Java解析Excel文件并把数据存入数据库

本文详细介绍了如何使用SpringMVC和Hibernate框架进行Web应用开发,包括web.xml配置、multipartfileupload、前端HTML表单、DAO和Service接口实现,以及读取和处理Excel数据的过程。
摘要由CSDN通过智能技术生成

使用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">

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

3. 文件上传的前端HTML

注意:

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

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

3.action=“${text}/uploadfile”

支持的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.rahttp://ndomUUID().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";

}
  • 6
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

月球程序猿

你的鼓励将是我创作的最大动

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值