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 进行了格式化 结果为:
随机推荐
- JBOSS整套开发组件整合和配置方法
http://blog.csdn.net/laigood/article/details/5743712主要是集成jboss,jboss esb,jboss portal,jboss seam,jbo ...
- ubuntu下创建.net core时出现 Failed to create prime the NuGet cache
https://docs.microsoft.com/en-us/aspnet/core/getting-started 根据微软给出的文档运行第一个web程序出现错误 Failed to creat ...
- java反射调用某个对象的方法
// 反射调用某个对象的方法 public Object invokeMethod(Object methodObject, String methodName, Object[] args) thr ...
- Spark-shell 启动WARN---java.net.BindException: Address already in use
同时打开了两个SecureCRT的终端界面,其中一个已经进入了Spark-shell,在另一个SecureCRT界面中执行 "spark-shell --master yarn --depl ...
- 181213 - 解决Android的应用APP背景色突然被改变的问题
在魅族最新的特定版本出现APP背景突然被改变颜色的问题 出问题的机型相关信息 型号:魅族16th Plus Android 版本: 8.1.0 安全补丁 版本: 2018年10月1日 Flyme 版本 ...
- asp.net mvc5 配置自定义路径
首先配置路由文件,默认页是第一个路由的配置: using System; using System.Collections.Generic; using System.Linq; using Syst ...
- excel增加上一列的数值(日期)
=TEXT(D2-1,"m月d日") 有年的话就是 =TEXT(D2-1,"yyyy年m月d日") D2就是参照日期
- 【flink training】 打车热点区域实时统计PopularPlaces
http://training.data-artisans.com/是Apache Flink商业公司DataArtisans提供的一个flink学习平台,主要提供了一些业务场景和flink api结 ...
- mysql之mysqldump、mysqlimport
一.引言 前一段在做一个csv的导入工具,最麻烦的部分就是对csv文件的解析,最后,老大提醒说是不是考虑的过于麻烦了,由于当时考虑到mysql是允许指定导出的csv文件的格式的,所以考虑到想要兼容这种 ...
- SWT将系统图标保存为本地文件
public class SWTImage { public static void main(String[] args) { final Display display = ...