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

发布时间 - 2026-01-11 01:05:09    点击率:

前段时间做一个小项目,为了同时存储多条数据,其中有一个功能是解析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文件并存入数据库的全部代码。希望对大家的学习有所帮助,也希望大家多多支持。


# Java上传excel  # Java  # excel存入数据库  # java将Excel存入数据库  # java导出数据库的全部表到excel  # Java实现Excel导入导出数据库的方法示例  # Java如何将Excel数据导入到数据库  # Java实现上传Excel文件并导入数据库  # Java使用POI从Excel读取数据并存入数据库(解决读取到空行问题)  # 配置文件  # 文件上传  # 遍历  # 上传文件  # 的是  # 都是  # 文件扩展名  # 上传  # 也不  # 是因为  # 在这个  # 还可以  # 只需  # 我把  # 要把  # 两天  # 我用  # 用了  # 扩展名  # 花了 


相关栏目: 【 网站优化151355 】 【 网络推广146373 】 【 网络技术251813 】 【 AI营销90571


相关推荐: 制作旅游网站html,怎样注册旅游网站?  Laravel Octane如何提升性能_使用Laravel Octane加速你的应用  Python结构化数据采集_字段抽取解析【教程】  Laravel模型事件有哪些_Laravel Model Event生命周期详解  如何在腾讯云免费申请建站?  Android自定义控件实现温度旋转按钮效果  Laravel如何与Inertia.js和Vue/React构建现代单页应用  移动端脚本框架Hammer.js  Android使用GridView实现日历的简单功能  Edge浏览器如何截图和滚动截图_微软Edge网页捕获功能使用教程【技巧】  EditPlus中的正则表达式实战(5)  Laravel怎么实现模型属性转换Casting_Laravel自动将JSON字段转为数组【技巧】  网站制作大概要多少钱一个,做一个平台网站大概多少钱?  Laravel怎么集成Vue.js_Laravel Mix配置Vue开发环境  Laravel怎么使用Collection集合方法_Laravel数组操作高级函数pluck与map【手册】  为什么php本地部署后css不生效_静态资源加载失败修复技巧【技巧】  java获取注册ip实例  如何破解联通资金短缺导致的基站建设难题?  如何在宝塔面板中修改默认建站目录?  Win11怎么关闭透明效果_Windows11辅助功能视觉效果设置  Python并发异常传播_错误处理解析【教程】  Laravel表单请求验证类怎么用_Laravel Form Request分离验证逻辑教程  Win11怎么恢复误删照片_Win11数据恢复工具使用【推荐】  电商网站制作多少钱一个,电子商务公司的网站制作费用计入什么科目?  Laravel如何集成第三方登录_Laravel Socialite实现微信QQ微博登录  laravel怎么在请求结束后执行任务(Terminable Middleware)_laravel Terminable Middleware请求结束任务执行方法  Laravel如何编写单元测试和功能测试?(PHPUnit示例)  如何在云主机快速搭建网站站点?  Laravel怎么实现前端Toast弹窗提示_Laravel Session闪存数据Flash传递给前端【方法】  动图在线制作网站有哪些,滑动动图图集怎么做?  laravel怎么使用数据库工厂(Factory)生成带有关联模型的数据_laravel Factory生成关联数据方法  详解Nginx + Tomcat 反向代理 如何在高效的在一台服务器部署多个站点  如何快速上传自定义模板至建站之星?  Microsoft Edge如何解决网页加载问题 Edge浏览器加载问题修复  手机怎么制作网站教程步骤,手机怎么做自己的网页链接?  Linux系统运维自动化项目教程_Ansible批量管理实战  Laravel Livewire是什么_使用Laravel Livewire构建动态前端界面  在centOS 7安装mysql 5.7的详细教程  软银砸40亿美元收购DigitalBridge 强化AI资料中心布局  Laravel如何优雅地处理服务层_在Laravel中使用Service层和Repository层  如何在腾讯云服务器上快速搭建个人网站?  Python自动化办公教程_ExcelWordPDF批量处理案例  简历没回改:利用AI润色让你的文字更专业  Laravel队列任务超时怎么办_Laravel Queue Timeout设置详解  Android Socket接口实现即时通讯实例代码  如何在IIS7上新建站点并设置安全权限?  如何用已有域名快速搭建网站?  HTML透明颜色代码怎么让图片透明_给img元素加透明色的技巧【方法】  JS中对数组元素进行增删改移的方法总结  Laravel怎么配置.env环境变量_Laravel生产环境敏感数据保护与读取【方法】