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时解析日期的更多相关文章

  1. java导入excel时处理日期格式(已验证ok)

    在Excel中的日期格式,比如2009-12-24将其转化为数字格式时变成了40171,在用java处理的时候,读取的也将是40171.如果使用POI处理Excel中的日期类型的单元格时,如果仅仅是判 ...

  2. Java 使用poi导入excel,结合xml文件进行数据验证的例子(增加了jar包)

    ava 使用poi导入excel,结合xml文件进行数据验证的例子(增加了jar包) 假设现在要做一个通用的导入方法: 要求: 1.xml的只定义数据库表中的column字段,字段类型,是否非空等条件 ...

  3. java通过poi读取excel中的日期类型数据或自定义类型日期

    Java 读取Excel表格日期类型数据的时候,读出来的是这样的  12-十月-2019,而Excel中输入的是 2019/10/12 或 2019-10-12 poi处理excel时,当excel没 ...

  4. java使用POI进行 Excel文件解析

    package com.timevale.esign.vip.util; import java.io.File; import java.io.FileInputStream; import jav ...

  5. java 使用poi 导入Excel 数据到数据库

    由于我个人电脑装的Excel是2016版本的,所以这地方我使用了XSSF 方式导入 . 1先手要制定一个Excel 模板 把模板放入javaWeb工程的某一个目录下如图: 2模板建好了后,先实现模板下 ...

  6. java 使用poi导入Excel通用方法

    需要的jar: [XML] 纯文本查看 复制代码 ? 1 2 3 4 5 <dependency>             <groupId>org.apache.poi< ...

  7. Java使用POI导入Excel异常Cannot get a text value from a numeric cell 解决

    异常原因:Excel数据Cell有不同的类型,当我们试图从一个数字类型的Cell读取出一个字符串并写入数据库时,就会出现Cannot get a text value from a numeric c ...

  8. POI导入excel时读取excel数据的真实行数

    有很多时候会出现空的数据导致行数被识别多的情况 // 获取Excel表的真实行数 int getExcelRealRow(Sheet sheet) { boolean flag = false; fo ...

  9. poi导入Excel,数字科学记数法转换

    在这里分享一下使用poi 导入Excel时 把数字转换为科学记数法的解决方法: 就是使用DecimalFormat对 i 进行了格式化 结果为:

随机推荐

  1. 转 OAuth 2.0授权协议详解

    http://www.jb51.net/article/54948.htm 作者:阮一峰 字体:[增加 减小] 类型:转载 时间:2014-09-10我要评论 这篇文章主要介绍了OAuth 2.0授权 ...

  2. 微信模板消息php

    微信的模板消息需要认证的公众号后台申请 申请通过后就可以用平台定义的消息模板了 define('IN_ECS', true); require(dirname(__FILE__) . '/includ ...

  3. unity, StopAllCoroutines导致bug的解决办法

    StopAllCoroutines有时候不用不行. 但只要一用,就可能导致无穷无尽的bug. 原因是StopAllCoroutines会将当前脚本中所有coroutines都停掉,而没法做到只停掉我们 ...

  4. [求助] 关于DDR3的读写操作,看看我的流程对吗?

    [求助] 关于DDR3的读写操作,看看我的流程对吗? 最近简单调了一下KC705开发板上面的DDR3,型号是MT8JTF12864HZ-1G6:有时候加载程序后,发现读出数据不是写进去的,在这将我的操 ...

  5. Verilog语言:还真的是人格分裂的语言

    人气腹语术师天愿在现场披露了被人偶搭档夺取灵魂的腹语术师将妻子杀害的表演节目.天愿真的陷入了多重人格,命令自己杀害妻子和子的人偶的人格出现了.为了不(让自己)杀害和弟子登川有外遇的妻子,天愿提出委托想 ...

  6. 聊一聊Android的消息机制

    聊一聊Android的消息机制 侯 亮 1概述 在Android平台上,主要用到两种通信机制,即Binder机制和消息机制,前者用于跨进程通信,后者用于进程内部通信. 从技术实现上来说,消息机制还是比 ...

  7. 171. Anagrams【medium】

    Given an array of strings, return all groups of strings that are anagrams. Notice All inputs will be ...

  8. 735. Replace With Greatest From Right【medium】

    Given an array of integers, replace every element with the next greatest element (greatest element o ...

  9. 利用JMX统计远程JAVA进程的CPU和Memory

    http://songzi0206.iteye.com/blog/1541636 ******************** 从JAVA 5开始,JDK提供了一些JVM检测的API,这就是有名的java ...

  10. SPI—读写串行 FLASH

    SPI协议简介SPI 协议是由摩托罗拉公司提出的通讯协议(Serial Peripheral Interface),即串行外围设备接口,是一种高速全双工的通信总线.它被广泛地使用在 ADC. LCD ...