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. Linxu 监控命令总结

    free –m [root@web1476 ~]# free        total       used       free     shared    buffers     cached M ...

  2. golang使用sqlite

    安装问题 在import sqlite的时候,golang build 出现以下错误, exec: "gcc": executable file not found in %PAT ...

  3. angular绑定数据 使用循环输出列表数据

    <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <script sr ...

  4. CentOS erlang安装、emqtt

    安装erlang 如果未安装以后程序,请先安装依赖   $sudo yum install gcc gcc-c++ glibc-devel make ncurses-devel openssl-dev ...

  5. hdu1010Tempter of the Bone(dfs+奇偶剪枝)

    题目链接:pid=1010">点击打开链接 题目描写叙述:给定一个迷宫,给一个起点和一个终点.问是否能恰好经过T步到达终点?每一个格子不能反复走 解题思路:dfs+剪枝 剪枝1:奇偶剪 ...

  6. 181213 - 解决Android的应用APP背景色突然被改变的问题

    在魅族最新的特定版本出现APP背景突然被改变颜色的问题 出问题的机型相关信息 型号:魅族16th Plus Android 版本: 8.1.0 安全补丁 版本: 2018年10月1日 Flyme 版本 ...

  7. Application Architecture Determines Application Performance

     Application Architecture Determines Application Performance Randy Stafford AppliCATion ARCHiTECTuR ...

  8. Redis 的 fields 遇到的问题

    问题描述:本地和测试环境同使用一台redis服务器,本地环境和测试环境使用 key,fileds,value 中的fileds 来区分,例如 key fields value 004920c6eba1 ...

  9. 把一个project相关的jar放到project的lib文件夹中

    例如你有一个project名为xxx,/xxx 文件夹中有src.bin.等等,然后你手工创建一个lib文件夹,这样你就把解压出来的第三方lib(jar包,含javadoc)都放到lib文件夹中,这样 ...

  10. poj1182食物链--并查集

    动物王国中有三类动物A,B,C,这三类动物的食物链构成了有趣的环形.A吃B, B吃C,C吃A. 现有N个动物,以1-N编号.每个动物都是A,B,C中的一种,但是我们并不知道它到底是哪一种.有人用两种说 ...