poi 导入excel文件,日期格式的处理。
poi 定时任务导入excel到数据库
花费了一些时间是现实定时任务下excel文件的定时导入功能,因为放入的文件excel格式不一样,所以可以自定义枚举,与对应的文件名进行区分。
poi 版本是4.1.2
在这里插入代码片
``package com.ruoyi.base.task;import com.ruoyi.base.constants.FileTypeEnum;
import com.ruoyi.system.domain.MfhfTest;
import com.ruoyi.system.domain.TestDataInfo;
import com.ruoyi.system.service.IMfhfTestService;
import com.ruoyi.system.service.ITestDataInfoService;
import com.ruoyi.web.controller.common.CommonController;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
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.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;import java.io.*;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;@Component
@Configuration
@EnableScheduling
public class FileTask {//此处是配置文件种配置的要扫描文件的路径。@Value("${file.uploadUrl}")//获取文件的存储路径private String uploadUrl;@Value("${file.removeUrl}")//获取文件要移除路径private String removeUrl;@Autowiredprivate ITestDataInfoService itestDataInfoService;@Autowiredprivate IMfhfTestService iMfhfTestService;private static final Logger log = LoggerFactory.getLogger(CommonController.class);private final static String excel2003L =".xls"; //2003- 版本的excelprivate final static String excel2007U =".xlsx"; //2007+ 版本的excel/*** @Description:获取IO流中的数据,组装成List<List<Object>>对象* @param in,fileName* @return* @throws IOException*/public static List<List<Object>> getListByExcel(InputStream in, String fileName,String strName) throws Exception{List<List<Object>> list = null;//创建Excel工作薄Workbook work = getWorkbook(in,fileName);if(null == work){throw new Exception("创建Excel工作薄为空!");}Sheet sheet = null; //页数Row row = null; //行数Cell cell = null; //列数list = new ArrayList<List<Object>>();//遍历Excel中所有的sheetif (strName.contains(FileTypeEnum.DSI.getFileType())){for (int i = 0; i < work.getNumberOfSheets(); i++) {sheet = work.getSheetAt(i);if(sheet==null){continue;}//遍历当前sheet中的所有行for (int j = sheet.getFirstRowNum(); j <= sheet.getLastRowNum(); j++) {row = sheet.getRow(j);if(row==null||row.getFirstCellNum()==j){continue;}//遍历所有的列List<Object> li = new ArrayList<Object>();for (int y = row.getFirstCellNum(); y < row.getLastCellNum(); y++) {cell = row.getCell(y);li.add(getValue(cell));}list.add(li);}}}else if(strName.contains(FileTypeEnum.MFHF.getFileType())){for (int i = 0; i < work.getNumberOfSheets(); i++) {sheet = work.getSheetAt(i);if(sheet==null){continue;}//遍历当前sheet中的所有行for (int j = 2; j <= sheet.getLastRowNum(); j++) {row = sheet.getRow(j);if(row==null||row.getFirstCellNum()==j){continue;}//遍历所有的列List<Object> li = new ArrayList<Object>();for (int y = row.getFirstCellNum(); y < row.getLastCellNum(); y++) {cell = row.getCell(y);li.add(getValue(cell));}list.add(li);}}}return list;}/*** @Description:根据文件后缀,自适应上传文件的版本* @param inStr,fileName* @return* @throws Exception*/public static Workbook getWorkbook(InputStream inStr,String fileName) throws Exception{Workbook wb = null;String fileType = fileName.substring(fileName.lastIndexOf("."));if(excel2003L.equals(fileType)){wb = new HSSFWorkbook(inStr); //2003-}else if(excel2007U.equals(fileType)){wb = new XSSFWorkbook(inStr); //2007+}else{throw new Exception("解析的文件格式有误!");}return wb;}/*** @Description:对表格中数值进行格式化* @param cell* @return*///解决excel类型问题,获得数值public static String getValue(Cell cell) {String value = "";if(null==cell){return value;}switch (cell.getCellType()) {//数值型case NUMERIC:if (HSSFDateUtil.isCellDateFormatted(cell)) {//如果是date类型则 ,获取该cell的date值// Date date = HSSFDateUtil.getJavaDate(cell.getNumericCellValue());// SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");// value = format.format(date);SimpleDateFormat sdf = null;// 验证short值,根据不同的日期长度进行判断if (cell.getCellStyle().getDataFormat() == 14) {sdf = new SimpleDateFormat("yyyy/MM/dd");} else if (cell.getCellStyle().getDataFormat() == 21) {sdf = new SimpleDateFormat("HH:mm:ss");} else if (cell.getCellStyle().getDataFormat() == 22) {sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");} else {throw new RuntimeException("日期格式错误!!!");}Date date = cell.getDateCellValue();value = sdf.format(date);} else {// 纯数字Double big=new Double(cell.getNumericCellValue());value = big.toString();//解决1234.0 去掉后面的.0if(null!=value&&!"".equals(value.trim())){String[] item = value.split("[.]");if(1<item.length&&"0".equals(item[1])){value=item[0];}}}break;//字符串类型case STRING:value = cell.getStringCellValue();break;// 公式类型case FORMULA://读公式计算值value = String.valueOf(cell.getNumericCellValue());if (value.equals("NaN")) {// 如果获取的数据值为非法值,则转换为获取字符串value = cell.getStringCellValue();}break;// 布尔类型case BOOLEAN:value = " "+ cell.getBooleanCellValue();break;default:value = cell.getStringCellValue();}if("null".endsWith(value.trim())){value="";}return value;}@Scheduled(cron = "0/10 * * * * ?")public void fileUpload() throws Exception {log.info("开始进入文件扫描的程序..................");//文件存储的初始位置String saveUrl = uploadUrl;//文件被剪切到的位置String remUrl = removeUrl;log.info("存储文件的地址为" + saveUrl);File file = new File(saveUrl);if(!file.exists()){//如果保存的uploadUrl文件夹不存在file.mkdir();//创建文件夹}File file1 = new File(remUrl);if(!file1.exists()){//如果保存的removeUrl文件夹不存在file1.mkdir();//创建文件夹}//遍历saveURl文件下的目录和文件File[] files = file.listFiles();for (File fs : files) {//获取文件名String fileName = fs.getName();String strName = fileName.replaceAll("[.][^.]+$", "");//获取文件的后缀名String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);//非目录(即文件是为excel文件.xls)则处理文件,数据插入到库中String filepath = uploadUrl + "/" + fileName;FileInputStream inputStream = new FileInputStream(new File(filepath));//获取到文件中数据的listList<List<Object>> list = FileTask.getListByExcel(inputStream, filepath,strName);//boolean flag = strName.contains(FileType.DSI.getFileType());// if (FileType.DSI.getFileType().equals(strName)) {//FileType是自定义的枚举,为了区分应该数据插入到那个实体类。if (strName.contains(FileTypeEnum.DSI.getFileType()) == true && list.size() > 0) {for (List<Object> list2 : list) {TestDataInfo testDataInfo = new TestDataInfo();testDataInfo.setNo(String.valueOf(list2.get(0)));testDataInfo.setSource(String.valueOf(list2.get(1)));testDataInfo.setStoreTime(String.valueOf(list2.get(2)));testDataInfo.setSampleType(String.valueOf(list2.get(3)));testDataInfo.setCheckData(String.valueOf(list2.get(4)));testDataInfo.setCheckDate(String.valueOf(list2.get(5)));testDataInfo.setCheckName(String.valueOf(list2.get(6)));int sum = itestDataInfoService.insertTes(testDataInfo);try {if (sum == 1) {//成功}} catch (Exception e) {//失败e.printStackTrace();}}//面粉加工精度}else if (strName.contains(FileTypeEnum.MFHF.getFileType()) == true && list.size() > 0){for (List<Object> list2 : list){MfhfTest mfhfTest = new MfhfTest();mfhfTest.setCsrq(String.valueOf(list2.get(0)));mfhfTest.setCssj(String.valueOf(list2.get(1)));mfhfTest.setScrq(String.valueOf(list2.get(2)));mfhfTest.setBc(String.valueOf(list2.get(3)));mfhfTest.setPm(String.valueOf(list2.get(4)));mfhfTest.setFxmj(String.valueOf(list2.get(5)));mfhfTest.setHdmj(String.valueOf(list2.get(6)));mfhfTest.setMfbd(String.valueOf(list2.get(7)));mfhfTest.setHfhl(String.valueOf(list2.get(8)));mfhfTest.setCs1(String.valueOf(list2.get(9)));mfhfTest.setCs2(String.valueOf(list2.get(10)));mfhfTest.setCs3(String.valueOf(list2.get(11)));mfhfTest.setLzhi(String.valueOf(list2.get(12)));mfhfTest.setAzhi(String.valueOf(list2.get(13)));mfhfTest.setBzhi(String.valueOf(list2.get(14)));int sum = iMfhfTestService.insertMfhf(mfhfTest);try{if (sum == 1){//成功}}catch (Exception e){//失败e.printStackTrace();}}}else if (strName.contains(FileTypeEnum.LSY.getFileType()) == true && list.size() > 0){//等等,其他的文件类型}InputStream inStream = new FileInputStream(filepath); //读入原文件String removeremoveUrl = removeUrl +"/"+ fileName;FileOutputStream removeFs = new FileOutputStream(removeremoveUrl);try {int bytesum = 0;int byteread = 0;byte[] buffer = new byte[1444];int length;while ((byteread = inStream.read(buffer)) != -1) {bytesum += byteread; //字节数 文件大小System.out.println(bytesum);removeFs.write(buffer, 0, byteread);}inputStream.close();inStream.close();removeFs.close();boolean flag = false;flag = deleteFile(fs);if (flag){log.info("删除文件成功");}// fs.delete();} catch (Exception e) {log.error("复制单个文件操作出错");e.printStackTrace();}}}/*** 删除文件** @param file* @return boolean*/private static boolean deleteFile(File file) {return file.delete();}}***
因为是小白,所以很多的判断可能欠缺。欢迎指正。
poi 导入excel文件,日期格式的处理。相关推荐
- 若依POI导入Excel多种日期格式转换为一种
项目需求,excel表格里有多种日期的字段,可能单元为date的,也可能为文本的自己手动填写的,要求后台保存为统一格式,yyyy/MM/dd. 因为数据库的日期字段的类型为字符串,所以保存到数据库的实 ...
- 如何优雅的用POI导入Excel文件
在企业级项目开发中,要经常涉及excel文件和程序之间导入导出的业务要求,那么今天来讲一讲excel文件导入的实现.java实现对excel的操作有很多种方式,例如EasyExcel等,今天我们使用的 ...
- web端实现表单提交poi导入excel文件
<!--虎牌导入会员数据--> <a class="btn btn-primary btn-sm search-btn btn-wide btn-scroll btn-sc ...
- Java导入Excel文件日期解析成了中文问题解决
Excel文件日期为2018-12-12,在解析出来的时候变成了 12-十二月-2018 cell.setCellType(Cell.CELL_TYPE_STRING);//根据不同类型转化成字符串 ...
- POI导入Excel文件(包含.xsl和.xslx文件兼容问题)
导入文件这里,分为了几个部分: 第一步是读取文件,若未读取到文件,直接返回读取失败信息: 第二步是读取到文件后,进行校验,若不是excel文件,返回文件格式错误,读取失败信息: 第三步是读取sheet ...
- POI 导入excel文件( 一 )
0.介绍 Apache POI 是基于 Office Open XML 标准(OOXML)和 Microsoft 的 OLE 2 复合文档格式(OLE2)处理各种文件格式的开源项目. 简而言之,您可以 ...
- POI对Excel自定义日期格式的读取
用POI读取Excel数据:(版本号:POI3.7) 1.读取Excel Java代码 private List<String[]> rosolveFile(InputStream i ...
- 导入EXCEL处理 日期格式
List item //获取单元格各类型值,返回字符串类型 public static String getCellValueByCell(Cell cell) { //判断是否为null或空串 if ...
- 使用poi导入Excel文件兼容性问题,The supplied data appears to be in the OLE2 Format.
今天在处理Excel文件时候,发现对于以xls和xlsx为后缀的文件,用以下的代码处理时候抛 The supplied data appears to be in the OLE2 Format.异常 ...
最新文章
- MySQL如何快速插入数据
- Java项目:高校学生社团活动管理系统(java+springboot+freemark+jpa+mysql)
- leetcode算法题--二维区域和检索 - 矩阵不可变
- 使用p3p跨域设置Cookie
- pipe实现单工和半双工模式
- mysql查看服务器版本sql_云服务器Windows系统查看mysql版本
- “37岁,年薪50万,一夜被裁”:伪上班,毁掉了多少中国年轻人
- MSCRM4.0商机移除价目表引起的问题
- 微信背后的产品观---张小龙内部8小时演讲
- Linux相关配置VMware安装
- 赫尔期权、期货及其他衍生产品第9版课后答案
- 心灵之火的瞬间-第二则
- 精密划片机维护及保养
- 世界再大,大不过一盘番茄炒蛋
- Android 中短信数据库的简单操作
- Maven编译Docker 镜像并推送到Nexus
- 老程序员吐槽,今天面试了一个被培训班坑了的学生
- TCP和UDP的区别有哪些
- JVM-调优《常见可视化工具与命令行的使用》
- 计算机网络大赛英文简称是什么,关于“中国高校计算机大赛网络技术挑战赛”(2018年)的通知...
热门文章
- GB50016计算机房设计规定,建筑设计防火规范 [附条文说明] GB50016-2014
- Probit模型、Logit模型、IV-Probit模型、IV-Probit模型
- 弘康人寿借助区块链技术公开全部理赔结果
- 百度ueditor自适应(编辑器自适应页面,图片上传宽高,等)
- 已从事软件测试10年,入行迷茫的你是否具备这个行业的硬+软实力!
- 深度学习笔记-计算机视觉、机器视觉以及数字图像处理之间的区别
- AJP:rTMS急性神经可塑性对抑郁症治疗结果的预测价值
- FCC认证是什么流程周期?
- Java代码调用聚合数据---查询全国车辆违章接口返回违章结果
- 【【SpringBoot系列】最详细demo--自定义日志脱敏组件,简单3 步完成 Spring Boot 的日志脱敏