java的poi导入excel时解析日期
if (r.getCellType()==Cell.CELL_TYPE_NUMERIC){
if(HSSFDateUtil.isCellDateFormatted(r)){
//用于转化为日期格式
Date d = r.getDateCellValue();
DateFormat formater = new SimpleDateFormat("yyyy-MM");
value = formater.format(d);
}else {
BigDecimal bigDecimal = new BigDecimal(r.getNumericCellValue());
value = bigDecimal.toString();
}
}else if (r.getCellType()==Cell.CELL_TYPE_STRING){
value=StringUtil.replaceBlank(r.getStringCellValue());
}else if(r.getCellType()==Cell.CELL_TYPE_BLANK){
}
、、、、、、、、、、、、、、、、、、、、、、、、、
package com.jianwu.manager.impl; import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.jianwu.constant.Constant;
import com.jianwu.dao.*;
import com.jianwu.domain.*;
import com.jianwu.manager.QiNiuManager;
import com.jianwu.manager.SalaryLeadManager;
import com.jianwu.rongClound.util.HttpUtil;
import com.jianwu.util.StringUtil;
import com.jianwu.util.excel.ExcelUtil;
import com.jianwu.util.excel.ExcelValidate;
import com.jianwu.util.excel.PoiUtil;
import com.jianwu.xct.domain.LoginMember;
import com.nodewind.core.web.cookyjar.Cookyjar;
import com.nodewind.service.result.Result;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile; import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.regex.Pattern; /**
* @Author lijin <tookbra@outlook.com>
* @Date 2017/9/22 12:07
* @Version
*/
@Service
@Transactional(readOnly = false)
public class SalaryLeadManagerImpl implements SalaryLeadManager {
private static final Logger logger = LoggerFactory.getLogger(SalaryLeadManagerImpl.class); @Autowired
QiNiuManager qiNiuManager; @Autowired
PaySalaryDao paySalaryDao; @Autowired
PaySalaryTemplateDao paySalaryTemplateDao; @Autowired
PaySalaryHomepageDao paySalaryHomepageDao; @Autowired
PaySalaryLeadRecordDao paySalaryLeadRecordDao; @Autowired
PayUserDao payUserDao; /* @Override
public Result readExcel(MultipartFile file, String suffix) {
InputStream inputStream = null;
try {
inputStream = file.getInputStream();
} catch (IOException e) {
System.out.println("文件提取错误:{}" + e);
return Result.error("文件提取错误");
}
return this.uploadEmployee(inputStream, suffix);
}*/ public Result uploadEmployee(InputStream inputStream, String suffix) {
if (suffix.equals(Constant.OFFICE_EXCEL_XLS)) {
try {
POIFSFileSystem fs = new POIFSFileSystem(inputStream);
HSSFWorkbook wb = new HSSFWorkbook(fs, true);
return this.preImportEmployee(wb);
} catch (IOException e) {
System.out.println("文件提取错误:{}" + e);
return Result.error("文件解析错误");
}
} else if (suffix.equals(Constant.OFFICE_EXCEL_XLSX)) {
System.out.println("文件提取错误:{}" + suffix);
return Result.error("文件解析错误");
}
System.out.println("文件解析错误");
return Result.error("文件解析错误");
} private Result<ExcelResult1> preImportEmployee(HSSFWorkbook wb) {
// Pattern p = Pattern.compile("^((13[0-9])|(15[^4,\\D])|(18[0,5-9]))\\d{8}$");
// String pattern = "\\d+";
String pattern = "^1\\d{10}";//手机号以1开头11位长度 ExcelResult1 excelResult = new ExcelResult1();
int sheets = wb.getNumberOfSheets();
if (sheets != 1) {
return Result.error("Excel模板错误,请下载最新的Excel模板文件后按格式增加员工信息1");
}
//Sheet sheet = wb.getSheet(tempName);
Sheet sheet = wb.getSheetAt(0);
if (sheet == null) {
return Result.error("Excel模板错误,请下载最新的Excel模板文件后按格式增加员工信息2");
} if(sheet.getLastRowNum() < 1) {
return Result.error("Excel表格中没有数据");
}
ExcelInfo1 excelInfo = null;
List<ExcelInfo1> excelInfos = new ArrayList<>();
List<ExcelInfo1> excelErrorInfos = new ArrayList<>();
List titleList = Lists.newArrayList();
//读取表头
Row titleRow = sheet.getRow(0);
//头部放入list
int len = sheet.getLastRowNum();
List<UploadSalary> uploadSalaries=new ArrayList<UploadSalary>(); for (int i = 1; i <=len; i++) {
UploadSalary uploadSalary = new UploadSalary();
uploadSalaries.add(uploadSalary);
Row row = sheet.getRow(i);
for (Cell r : row) {
String title = StringUtil.replaceBlank(titleRow.getCell(r.getColumnIndex()).getStringCellValue());
String value="";
if (r.getCellType()==Cell.CELL_TYPE_NUMERIC){
if(HSSFDateUtil.isCellDateFormatted(r)){
//用于转化为日期格式
Date d = r.getDateCellValue();
DateFormat formater = new SimpleDateFormat("yyyy-MM");
value = formater.format(d);
}else {
BigDecimal bigDecimal = new BigDecimal(r.getNumericCellValue());
value = bigDecimal.toString();
}
}else if (r.getCellType()==Cell.CELL_TYPE_STRING){
value=StringUtil.replaceBlank(r.getStringCellValue());
}else if(r.getCellType()==Cell.CELL_TYPE_BLANK){ }
if ("姓名".equals(title)) {
uploadSalary.setName(value);
} else if ("手机号".equals(title)) {
if(Pattern.matches(pattern, value)){
uploadSalary.setPhone(value);
}else{
return Result.error("存在格式不正确的手机号码,请修改后重新导入!");
}
} else if ("月份".equals(title)) {
uploadSalary.setMonth(value);
}else{
PaySalaryItem paySalaryItem=new PaySalaryItem();
paySalaryItem.setItemName(title);
Double v=0d;
try {
v = Double.valueOf(value);
}catch (Exception e){
e.printStackTrace();
}
paySalaryItem.setSalary(BigDecimal.valueOf(v));
uploadSalary.addPaySalaryItem(paySalaryItem);
}
}
System.out.println(uploadSalaries);
} Cell cell = null;
//验证必填字段
try {
int errorCount = 0;
for (UploadSalary uploadSalary : uploadSalaries) {
if (errorCount > 50) {
break;
}
excelInfo = new ExcelInfo1();
String errorMsg = ExcelValidate.valid(uploadSalary);
uploadSalary.setErrorMsg(errorMsg);
excelInfo.setEmpInfo(uploadSalaries);
if (!Strings.isNullOrEmpty(errorMsg)) {
excelInfo.setError(true);
excelInfo.setErrorMsg(errorMsg);
excelErrorInfos.add(excelInfo);
} else {
excelInfo.setError(false);
excelInfos.add(excelInfo);
} }
} catch (Exception e) {
System.out.println("[preImportEmployee]: " + e);
e.printStackTrace();
return Result.error("");
}
excelResult.setExcelInfos(excelInfos);
excelResult.setExcelErrorInfos(excelErrorInfos);
excelResult.setTotal(uploadSalaries.size());
excelResult.setSheetName(sheet.getSheetName());
return Result.success(excelResult);
} @Override
@Transactional(readOnly = false, propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
public Result importEmployee(MultipartFile f, LoginMember loginMember,String tempName) throws Exception {
PayUser payUser = payUserDao.selectByPrimaryKey(loginMember.getId().intValue());
if(payUser.getStatus() == 0){
return Result.error("平台管理员不能导入!");
}
//todo 选择公司
Integer companyId = null;
if(StringUtils.isNotBlank(payUser.getCompanyIds())){
companyId = Integer.valueOf(payUser.getCompanyIds().split(",")[0]);
} PaySalaryHomepage paySalaryHomepage = paySalaryHomepageDao.queryByName(tempName, companyId);
if(null!=paySalaryHomepage){
// if(paySalaryHomepage.getOperId()==loginMember.getId().intValue()){
if(companyId.toString().equals(paySalaryHomepage.getCompanyIds()) && tempName.equals(paySalaryHomepage.getFilename())){
return Result.error("已经有此文件");
}else {
Result<ExcelResult1> result = this.uploadEmployee(f.getInputStream(), ".xls");
int size_ = 0;
if (result.isSuccess()) {
ExcelResult1 excelResult = result.getData();
if (excelResult.getExcelErrorInfos().size() > 0) {
return Result.error("错误");
} else {
Long templateId = paySalaryTemplateDao.queryId(excelResult.getSheetName(), companyId);
if(null==templateId){
return Result.error("此模板已经被删除!");
}
List<ExcelInfo1> excelInfoList = excelResult.getExcelInfos();
size_ = excelInfoList.size();
PaySalaryLeadRecord paySalaryLeadRecord1 = new PaySalaryLeadRecord();
String time = null;
for (ExcelInfo1 excelInfo : excelInfoList) {
List<UploadSalary> uploadSalary = excelInfo.getEmpInfo();
time = uploadSalary.get(0).getMonth();
for (UploadSalary uploadSalary2:uploadSalary){
if(!uploadSalary2.getMonth().equals(time)){
return Result.error("工资单人员月份不一样!");
}
} for (UploadSalary uploadSalary1:uploadSalary){
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM");//小写的mm表示的是分钟
PaySalary paySalary = new PaySalary();
paySalary.setPhone(uploadSalary1.getPhone());
paySalary.setName(uploadSalary1.getName());
paySalary.setMonth(sdf.parse(uploadSalary1.getMonth()));
paySalary.setOperId(loginMember.getId().intValue());
paySalary.setTemplateId(templateId.intValue()); SimpleDateFormat sdf1=new SimpleDateFormat("yyyy-MM-dd");
Date date = sdf1.parse(uploadSalary1.getMonth()+"-01");
System.out.println("==============>月份:"+date); List<String> strings=new ArrayList<>();
String salarys = "";
for(PaySalaryItem paySalaryItem:uploadSalary1.getItemName()){
strings.add(paySalaryItem.getItemName()+":"+paySalaryItem.getSalary());
}
salarys= StringUtils.join(strings,",");
// Integer id = paySalaryDao.queryByName(uploadSalary1.getPhone(),sdf1.parse(uploadSalary1.getMonth()+"-01"));
if(payUser.getStatus() != 0){
paySalary.setCompanyIds(companyId.toString());
}
if(StringUtils.isNotEmpty(salarys)){
paySalary.setSalarytext(salarys);
paySalaryDao.insertSelective(paySalary);
//paySalaryDao.insertSalary(salarys,id);
}
Integer id = paySalaryDao.queryByName(uploadSalary1.getPhone(),sdf1.parse(uploadSalary1.getMonth()+"-01")); paySalaryLeadRecord1.setEmpId(id);
paySalaryLeadRecord1.setFilename(tempName);
if(payUser.getStatus() != 0){
paySalaryLeadRecord1.setCompanyIds(companyId.toString());
}
paySalaryLeadRecordDao.insertSelective(paySalaryLeadRecord1);
//leadCount=leadCount++;
}
break;
}
PaySalaryHomepage paySalaryHomepage1 = new PaySalaryHomepage();
//Long leadCount = paySalaryDao.queryCountById(templateId);
Long leadCount = paySalaryLeadRecordDao.queryLikeSum(tempName,"","");
if(null!=leadCount){
paySalaryHomepage1.setLeadCount(leadCount);
}else {
paySalaryHomepage1.setLeadCount(0L);
}
paySalaryHomepage1.setFilename(tempName);
paySalaryHomepage1.setTemplateId(templateId.intValue());
paySalaryHomepage1.setOperId(loginMember.getId().intValue());
if(payUser.getStatus() != 0){
paySalaryHomepage1.setCompanyIds(companyId.toString());
}
paySalaryHomepageDao.insertSelective(paySalaryHomepage1);//导入工资单后添加一条记录 }
}
return result;
}
}else{
Result<ExcelResult1> result = this.uploadEmployee(f.getInputStream(), ".xls");
int size_ = 0;
if (result.isSuccess()) {
ExcelResult1 excelResult = result.getData();
if (excelResult.getExcelErrorInfos().size() > 0) {
return Result.error("错误");
} else {
Long templateId = paySalaryTemplateDao.queryId(excelResult.getSheetName(), companyId);
if(null==templateId){
return Result.error("此模板已经被删除!");
}
List<ExcelInfo1> excelInfoList = excelResult.getExcelInfos();
size_ = excelInfoList.size();
PaySalaryLeadRecord paySalaryLeadRecord1 = new PaySalaryLeadRecord();
String time = null;
for (ExcelInfo1 excelInfo : excelInfoList) {
List<UploadSalary> uploadSalary = excelInfo.getEmpInfo();
time = uploadSalary.get(0).getMonth();
for (UploadSalary uploadSalary2:uploadSalary){
if(time == null || uploadSalary2.getMonth() == null){
return Result.error("工资单月份不能为空且格式为:yyyy-MM,如:2018-01");
}
if(!uploadSalary2.getMonth().equals(time)){
return Result.error("工资单人员月份不一样!");
}
} for (UploadSalary uploadSalary1:uploadSalary){
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM");//小写的mm表示的是分钟
PaySalary paySalary = new PaySalary();
paySalary.setPhone(uploadSalary1.getPhone());
paySalary.setName(uploadSalary1.getName());
paySalary.setMonth(sdf.parse(uploadSalary1.getMonth()));
paySalary.setOperId(loginMember.getId().intValue());
paySalary.setTemplateId(templateId.intValue()); SimpleDateFormat sdf1=new SimpleDateFormat("yyyy-MM-dd");
Date date = sdf1.parse(uploadSalary1.getMonth()+"-01");
System.out.println("==============>月份:"+date); List<String> strings=new ArrayList<>();
String salarys = "";
for(PaySalaryItem paySalaryItem:uploadSalary1.getItemName()){
strings.add(paySalaryItem.getItemName()+":"+paySalaryItem.getSalary());
}
salarys= StringUtils.join(strings,",");
// Integer id = paySalaryDao.queryByName(uploadSalary1.getPhone(),sdf1.parse(uploadSalary1.getMonth()+"-01"));
if(payUser.getStatus() != 0){
paySalary.setCompanyIds(companyId.toString());
}
if(StringUtils.isNotEmpty(salarys)){
paySalary.setSalarytext(salarys);
paySalaryDao.insertSelective(paySalary);
//paySalaryDao.insertSalary(salarys,id);
}
Integer id = paySalaryDao.queryByName(uploadSalary1.getPhone(),sdf1.parse(uploadSalary1.getMonth()+"-01")); paySalaryLeadRecord1.setEmpId(id);
paySalaryLeadRecord1.setFilename(tempName);
if(payUser.getStatus() != 0){
paySalaryLeadRecord1.setCompanyIds(companyId.toString());
}
paySalaryLeadRecordDao.insertSelective(paySalaryLeadRecord1);
//leadCount=leadCount++;
}
break;
}
PaySalaryHomepage paySalaryHomepage1 = new PaySalaryHomepage();
//Long leadCount = paySalaryDao.queryCountById(templateId);
Long leadCount = paySalaryLeadRecordDao.queryLikeSum(tempName,"","");
if(null!=leadCount){
paySalaryHomepage1.setLeadCount(leadCount);
}else {
paySalaryHomepage1.setLeadCount(0L);
}
paySalaryHomepage1.setFilename(tempName);
paySalaryHomepage1.setTemplateId(templateId.intValue());
paySalaryHomepage1.setOperId(loginMember.getId().intValue());
if(payUser.getStatus() != 0){
paySalaryHomepage1.setCompanyIds(companyId.toString());
}
paySalaryHomepageDao.insertSelective(paySalaryHomepage1);//导入工资单后添加一条记录 }
}
return result;
}
}
}
java的poi导入excel时解析日期的更多相关文章
- java导入excel时处理日期格式(已验证ok)
在Excel中的日期格式,比如2009-12-24将其转化为数字格式时变成了40171,在用java处理的时候,读取的也将是40171.如果使用POI处理Excel中的日期类型的单元格时,如果仅仅是判 ...
- Java 使用poi导入excel,结合xml文件进行数据验证的例子(增加了jar包)
ava 使用poi导入excel,结合xml文件进行数据验证的例子(增加了jar包) 假设现在要做一个通用的导入方法: 要求: 1.xml的只定义数据库表中的column字段,字段类型,是否非空等条件 ...
- java通过poi读取excel中的日期类型数据或自定义类型日期
Java 读取Excel表格日期类型数据的时候,读出来的是这样的 12-十月-2019,而Excel中输入的是 2019/10/12 或 2019-10-12 poi处理excel时,当excel没 ...
- java使用POI进行 Excel文件解析
package com.timevale.esign.vip.util; import java.io.File; import java.io.FileInputStream; import jav ...
- java 使用poi 导入Excel 数据到数据库
由于我个人电脑装的Excel是2016版本的,所以这地方我使用了XSSF 方式导入 . 1先手要制定一个Excel 模板 把模板放入javaWeb工程的某一个目录下如图: 2模板建好了后,先实现模板下 ...
- java 使用poi导入Excel通用方法
需要的jar: [XML] 纯文本查看 复制代码 ? 1 2 3 4 5 <dependency> <groupId>org.apache.poi< ...
- Java使用POI导入Excel异常Cannot get a text value from a numeric cell 解决
异常原因:Excel数据Cell有不同的类型,当我们试图从一个数字类型的Cell读取出一个字符串并写入数据库时,就会出现Cannot get a text value from a numeric c ...
- POI导入excel时读取excel数据的真实行数
有很多时候会出现空的数据导致行数被识别多的情况 // 获取Excel表的真实行数 int getExcelRealRow(Sheet sheet) { boolean flag = false; fo ...
- poi导入Excel,数字科学记数法转换
在这里分享一下使用poi 导入Excel时 把数字转换为科学记数法的解决方法: 就是使用DecimalFormat对 i 进行了格式化 结果为:
随机推荐
- Linux su命令参数及用法详解--Linux切换用户命令
建议大家切换用户的时候 使用 su - root 这样,否则可能发现某些命令执行不了 关于su .su - 及 sudo的区别 请往下看 1.命令作用 su的作用是变更为其它使用者的身份,超级用 ...
- canvas学习笔记(中篇) -- canvas入门教程-- 颜色/透明度/渐变色/线宽/线条样式/虚线/文本/阴影/图片/像素处理
[中篇] -- 建议学习时间4小时 课程共(上中下)三篇 此笔记是我初次接触canvas的时候的学习笔记,这次特意整理为博客供大家入门学习,几乎涵盖了canvas所有的基础知识,并且有众多练习案例, ...
- win7保护眼睛的颜色设置方法(85,125,205)
win7保护眼睛的颜色设置方法(85,125,205) 在电脑桌面空白处点击右键“个性化”按钮. 在弹出的对话框单击“窗口颜色”. 在弹出的新的对话框中单击“高级外观设置”. 在弹出的窗口颜色和外观中 ...
- C# OO(初级思想)
继承,多态,封装 在C#中,为了能够合理描述自然界的规律,面向对象的编程引入了继承的概念,是面向对象编程中最重要的概念之一,定义了如何根据现有的类创建新类的过程. 继承:一个类派生出来的子类具有这个类 ...
- Android studio使用心得(二)— 打包签名apk发布
1.—–Android Studio菜单 Build->Generate Signed APK 2.——Create new.. 3.——-跟eclipse里面一样,添加keystore 信 ...
- Linux下自动备份Oracle数据库并删除指定天数前的备份
说明: Oracle数据库服务器 操作系统:CentOS IP:192.168.0.198 端口:1521 SID:orcl Oracle数据库版本:Oracle11gR2 具体操作: 1.root用 ...
- 使用 xlue 实现 tips
经常遇到如下的需求 鼠标hover到目标对象一定时间后,弹出tips或者窗口; 鼠标离开目标对象一定时间后,隐藏tips或者窗口; 鼠标从目标对象移动到弹出的窗口上,这种状况下不隐藏窗口; 考虑到这种 ...
- 跟着百度学PHP[17]-PHP扩展CURL的模拟登陆并获取数据
这两天也不知道怎么,学习效率低.很无奈. 如何知道要去URL该怎么填写呢?就是填写表单中的Action内容: tempnam() 函数创建一个具有唯一文件名的临时文件. <?php header ...
- NumberUtils
package cn.edu.hbcf.common.utils; import java.math.BigDecimal; import java.text.NumberFormat; import ...
- 机器学习算法( 五、Logistic回归算法)
一.概述 这会是激动人心的一章,因为我们将首次接触到最优化算法.仔细想想就会发现,其实我们日常生活中遇到过很多最优化问题,比如如何在最短时间内从A点到达B点?如何投入最少工作量却获得最大的效益?如何设 ...