excel导入导出

This commit is contained in:
钱涛 2022-03-07 15:08:56 +08:00 committed by Chengliang
parent 91958201e5
commit 880cf9ef66
14 changed files with 751 additions and 33 deletions

View File

@ -1,8 +1,11 @@
package com.engine.salary.biz;
import com.engine.salary.entity.datacollection.AddUpDeduction;
import com.engine.salary.entity.datacollection.DataCollectionEmployee;
import com.engine.salary.entity.datacollection.dto.AddUpDeductionListDTO;
import com.engine.salary.entity.datacollection.param.AddUpDeductionQueryParam;
import com.engine.salary.mapper.datacollection.AddUpDeductionMapper;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.ibatis.session.SqlSession;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.CellType;
@ -21,7 +24,7 @@ public class AddUpDeductionBiz extends BaseBean {
/**
* 查询列表
* 关联查询查询列表
*
* @param param
* @return
@ -30,8 +33,75 @@ public class AddUpDeductionBiz extends BaseBean {
SqlSession sqlSession = MyBatisFactory.sqlSessionFactory.openSession();
try {
AddUpDeductionMapper mapper = sqlSession.getMapper(AddUpDeductionMapper.class);
List<AddUpDeductionListDTO> list = mapper.list(param);
return list;
return mapper.list(param);
} finally {
sqlSession.close();
}
}
/**
* 条件查询
*
* @param param
* @return
*/
public List<AddUpDeduction> listSome(AddUpDeduction param) {
SqlSession sqlSession = MyBatisFactory.sqlSessionFactory.openSession();
try {
AddUpDeductionMapper mapper = sqlSession.getMapper(AddUpDeductionMapper.class);
return mapper.listSome(param);
} finally {
sqlSession.close();
}
}
/**
* 批量插入
*
* @param param
* @return
*/
public void batchSave(List<AddUpDeduction> param) {
SqlSession sqlSession = MyBatisFactory.sqlSessionFactory.openSession();
try {
AddUpDeductionMapper mapper = sqlSession.getMapper(AddUpDeductionMapper.class);
mapper.insertData(param);
sqlSession.commit();
} finally {
sqlSession.close();
}
}
/**
* 批量插入
*
* @param param
* @return
*/
public void batchUpdate(List<AddUpDeduction> param) {
SqlSession sqlSession = MyBatisFactory.sqlSessionFactory.openSession();
try {
AddUpDeductionMapper mapper = sqlSession.getMapper(AddUpDeductionMapper.class);
mapper.updateData(param);
sqlSession.commit();
} finally {
sqlSession.close();
}
}
/**
* 查询人员列表
*
* @return
*/
public List<DataCollectionEmployee> listEmployee() {
SqlSession sqlSession = MyBatisFactory.sqlSessionFactory.openSession();
try {
AddUpDeductionMapper mapper = sqlSession.getMapper(AddUpDeductionMapper.class);
return mapper.listEmployee();
} finally {
sqlSession.close();
}
@ -124,7 +194,7 @@ public class AddUpDeductionBiz extends BaseBean {
cellList.add(Util.null2String(dto.getMobile()));
cellList.add(Util.null2String(dto.getJobNum()));
cellList.add(Util.null2String(dto.getIdNo()));
cellList.add(dto.getHiredate()==null?"":formatter.format(dto.getHiredate()));
cellList.add(dto.getHiredate() == null ? "" : formatter.format(dto.getHiredate()));
cellList.add(String.valueOf(dto.getAddUpChildEducation()));
cellList.add(String.valueOf(dto.getAddUpContinuingEducation()));
cellList.add(String.valueOf(dto.getAddUpHousingLoanInterest()));
@ -140,4 +210,63 @@ public class AddUpDeductionBiz extends BaseBean {
return rowList;
}
public void handleImportData(List<AddUpDeduction> pos) {
if (CollectionUtils.isEmpty(pos)) {
return;
}
AddUpDeduction po = pos.get(0);
// 多条相同人的则以第一条为准如果逆序排列用于重复的则以最后一条为准Collections.reverse(pos);
// 去重通过记录的唯一条件(申报月份人员id个税扣缴义务人id)拼接
List<AddUpDeduction> finalPos = pos.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(f -> f.getEmployeeId() + "-" + f.getTaxAgentId()))), ArrayList::new));
// 查询已有数据
List<AddUpDeduction> list = listSome(AddUpDeduction.builder().declareMonth(po.getDeclareMonth()).build());
// 待修改的 本地已存在则更新交集
List<AddUpDeduction> updateList = list.stream().map(m -> {
Optional<AddUpDeduction> optional = finalPos.stream().filter(p -> (p.getEmployeeId() + "-" + p.getTaxAgentId()).equals(m.getEmployeeId() + "-" + m.getTaxAgentId())).findFirst();
AddUpDeduction temp = null;
if (optional.isPresent()) {
temp = optional.get();
// 换成本地库的id
temp.setId(m.getId());
}
return temp;
}).filter(Objects::nonNull).collect(Collectors.toList());
// 待新增的 导入比本地多则新增差集(导入 - local)
List<AddUpDeduction> saveList = finalPos.stream().map(m -> {
Optional<AddUpDeduction> optional = list.stream().filter(p -> (p.getEmployeeId() + "-" + p.getTaxAgentId()).equals(m.getEmployeeId() + "-" + m.getTaxAgentId())).findFirst();
AddUpDeduction temp = null;
if (!optional.isPresent()) {
temp = m;
}
return temp;
}).filter(Objects::nonNull).collect(Collectors.toList());
// 修改
if (CollectionUtils.isNotEmpty(updateList)) {
batchUpdate(updateList);
}
// 保存
if (CollectionUtils.isNotEmpty(saveList)) {
batchSave(saveList);
}
// 记录操作日志
// saveList.addAll(updateList);
//
// if (CollectionUtils.isNotEmpty(saveList)) {
// LoggerContext loggerContext = new LoggerContext();
// loggerContext.setTargetId(String.valueOf(IdGenerator.generate()));
// loggerContext.setTargetName(SalaryI18nUtil.getI18nLabel(message.getTenantKey(), message.getUserId(), 100351, "导入累计专项附加扣除"));
// loggerContext.setOperateType(OperateTypeEnum.ADD.getValue());
// loggerContext.setOperateTypeName(SalaryI18nUtil.getI18nLabel(message.getTenantKey(), message.getUserId(), 100351, "导入累计专项附加扣除"));
// loggerContext.setOperatedesc(SalaryI18nUtil.getI18nLabel(message.getTenantKey(), message.getUserId(), 100351, "导入累计专项附加扣除"));
// loggerContext.setNewValueList(saveList);
// loggerContext.setTenant_key(message.getTenantKey());
// loggerContext.setOperator(message.getUserId().toString());
// loggerContext.setOperatorName(message.getOpreator());
// loggerContext.setClientIp(message.getClientIp());
// addUpDeductionLoggerTemplate.write(loggerContext);
// }
}
}

View File

@ -0,0 +1,21 @@
package com.engine.salary.biz;
import com.engine.salary.entity.taxrate.TaxAgent;
import com.engine.salary.mapper.TaxAgentMapper;
import org.apache.ibatis.session.SqlSession;
import weaver.conn.mybatis.MyBatisFactory;
import java.util.List;
public class TaxAgentBiz {
public List<TaxAgent> listAll() {
SqlSession sqlSession = MyBatisFactory.sqlSessionFactory.openSession();
try {
TaxAgentMapper taxAgentMapper = sqlSession.getMapper(TaxAgentMapper.class);
return taxAgentMapper.listAll();
} finally {
sqlSession.close();
}
}
}

View File

@ -22,6 +22,14 @@ import weaver.general.BaseBean;
import java.util.*;
import java.util.stream.Collectors;
/**
* 税率操作类
* <p>Copyright: Copyright (c) 2022</p>
* <p>Company: 泛微软件</p>
*
* @author qiantao
* @version 1.0
**/
public class TaxRateBiz extends BaseBean {
@ -39,11 +47,9 @@ public class TaxRateBiz extends BaseBean {
taxRateBase = new TaxRateBase();
//fixme 逻辑可能有问题自定义和系统的id保持一致
if (sysTaxRateBase != null) {
BeanUtils.copyProperties(sysTaxRateBase, taxRateBase);
}
}
return taxRateBase;
} finally {
sqlSession.close();

View File

@ -8,6 +8,14 @@ import weaver.general.BaseBean;
import java.util.List;
/**
* 税率明细操作类
* <p>Copyright: Copyright (c) 2022</p>
* <p>Company: 泛微软件</p>
*
* @author qiantao
* @version 1.0
**/
public class TaxRateDetailBiz extends BaseBean {
public void saveBatch(List<TaxRateDetail> list) {

View File

@ -0,0 +1,236 @@
package com.engine.salary.cmd.datacollection;
import com.engine.common.biz.AbstractCommonCommand;
import com.engine.common.entity.BizLogContext;
import com.engine.core.interceptor.CommandContext;
import com.engine.salary.biz.AddUpDeductionBiz;
import com.engine.salary.biz.TaxAgentBiz;
import com.engine.salary.entity.datacollection.AddUpDeduction;
import com.engine.salary.entity.datacollection.DataCollectionEmployee;
import com.engine.salary.entity.datacollection.dto.AddUpDeductionListDTO;
import com.engine.salary.entity.datacollection.param.AddUpDeductionImportParam;
import com.engine.salary.entity.taxrate.TaxAgent;
import com.engine.salary.exception.SalaryRunTimeException;
import com.engine.salary.util.excel.ExcelParseHelper;
import com.google.common.collect.Maps;
import lombok.SneakyThrows;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.util.IOUtils;
import weaver.file.ImageFileManager;
import weaver.general.Util;
import weaver.hrm.User;
import javax.servlet.http.HttpServletRequest;
import java.io.InputStream;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;
import static com.engine.salary.constant.SalaryDefaultTenantConstant.DEFAULT_TENANT_KEY;
public class AddUpDeductionImportCmd extends AbstractCommonCommand<Map<String, Object>> {
protected HttpServletRequest request;
public AddUpDeductionImportCmd(Map<String, Object> params, User user) {
this.user = user;
this.params = params;
}
@Override
public BizLogContext getLogContext() {
return null;
}
@SneakyThrows
@Override
public Map<String, Object> execute(CommandContext commandContext) {
Map<String, Object> apidatas = new HashMap<String, Object>();
AddUpDeductionBiz addUpDeductionBiz = new AddUpDeductionBiz();
//检验参数
checkImportParam();
//导入参数
AddUpDeductionImportParam importParam = (AddUpDeductionImportParam) params.get("importParam");
//excel文件id
String imageId = Util.null2String(importParam.getImageId());
//税款所属期
String declareMonthStr = Util.null2String(importParam.getDeclareMonth());
//个税扣缴义务人
String taxAgentId = Util.null2String(importParam.getTaxAgentId());
InputStream fileInputStream = null;
// try {
fileInputStream = ImageFileManager.getInputStreamById(Integer.valueOf(imageId));
// fileInputStream = new FileInputStream("C:\\Users\\钱涛\\Desktop\\addUpDeductionTemplate.xlsx");
// } catch (FileNotFoundException e) {
// e.printStackTrace();
// }
try {
List<AddUpDeductionListDTO> addUpDeductions = ExcelParseHelper.parse(fileInputStream, AddUpDeductionListDTO.class, 0, 1, 12, "addUpDeductionTemplate.xlsx");
int total = addUpDeductions.size();
int index = 0;
int successCount = 0;
int errorCount = 0;
//人员信息
List<DataCollectionEmployee> employees = addUpDeductionBiz.listEmployee();
List<TaxAgent> taxAgents = new TaxAgentBiz().listAll();
//税款所属期
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
Date declareMonth = simpleDateFormat.parse(declareMonthStr + "-01");
// 错误excel内容
List<Map> errorData = new ArrayList<>();
//合规数据
List<AddUpDeduction> eligibleData = new ArrayList<>();
for (int i = 0; i < addUpDeductions.size(); i++) {
AddUpDeductionListDTO dto = addUpDeductions.get(i);
Date now = new Date();
//待插入数据库对象
AddUpDeduction addUpDeduction = AddUpDeduction.builder()
.tenantKey(DEFAULT_TENANT_KEY)
.createTime(now)
.updateTime(now)
.creator((long) user.getUID())
.declareMonth(declareMonth).build();
//异常点数量
int errorSum = 0;
//行号
String rowIndex = String.format("第%s行", i + 2);
//相同的姓名
String userName = dto.getUsername();
String deparmentName = dto.getDepartmentName();
List<Long> employeeSameIds = employees.stream().filter(e -> (StringUtils.isBlank(userName) || Objects.equals(e.getUsername(), userName))
&& (StringUtils.isBlank(deparmentName) || Objects.equals(e.getDeparmentName(), deparmentName))).map(DataCollectionEmployee::getEmployeeId)
.collect(Collectors.toList());
if (StringUtils.isBlank(userName)) {
//姓名 不能为空
//错误消息对象
Map<String, String> errorMessageMap = Maps.newHashMap();
errorMessageMap.put("message", rowIndex + "姓名不能为空");
errorData.add(errorMessageMap);
errorSum += 1;
} else if (CollectionUtils.isEmpty(employeeSameIds) || employeeSameIds.size() > 1) {
Map<String, String> errorMessageMap = Maps.newHashMap();
errorMessageMap.put("message", rowIndex + "员工信息不能为空且不可重复(姓名与部门同时确认唯一)");
errorData.add(errorMessageMap);
errorSum += 1;
} else {
Long employeeId = CollectionUtils.isNotEmpty(employeeSameIds) && employeeSameIds.size() == 1 ? employeeSameIds.get(0) : null;
if (employeeId != null && employeeId > 0) {
addUpDeduction.setEmployeeId(employeeId);
} else {
//姓名错误系统内不存在该姓名
Map<String, String> errorMessageMap = Maps.newHashMap();
errorMessageMap.put("message", rowIndex + "姓名错误,系统内不存在该姓名");
errorData.add(errorMessageMap);
errorSum += 1;
}
}
String taxAgentName = dto.getTaxAgentName();
if (StringUtils.isBlank(taxAgentName)) {
//个税扣缴义务人不能为空
Map<String, String> errorMessageMap = Maps.newHashMap();
errorMessageMap.put("message", rowIndex + "个税扣缴义务人不能为空");
errorData.add(errorMessageMap);
errorSum += 1;
} else {
Optional<TaxAgent> optionalTemp = taxAgents.stream().filter(m -> m.getName().equals(taxAgentName)).findFirst();
if (optionalTemp.isPresent()) {
if (StringUtils.isNotEmpty(taxAgentId) && !optionalTemp.get().getId().equals(Long.valueOf(taxAgentId))) {
//个税扣缴义务人与导入时选择的不一致
Map<String, String> errorMessageMap = Maps.newHashMap();
errorMessageMap.put("message", rowIndex + "个税扣缴义务人与导入时选择的不一致");
errorData.add(errorMessageMap);
errorSum += 1;
} else {
addUpDeduction.setTaxAgentId(optionalTemp.get().getId());
}
} else {
//个税扣缴义务人不存在
Map<String, String> errorMessageMap = Maps.newHashMap();
errorMessageMap.put("message", rowIndex + "个税扣缴义务人不存在");
errorData.add(errorMessageMap);
errorSum += 1;
}
}
//累计子女教育
BigDecimal addUpChildEducation = dto.getAddUpChildEducation();
addUpDeduction.setAddUpChildEducation(Util.null2String(addUpChildEducation));
//累计继续教育
BigDecimal addUpContinuingEducation = dto.getAddUpContinuingEducation();
addUpDeduction.setAddUpContinuingEducation(Util.null2String(addUpContinuingEducation));
//累计住房贷款利息
BigDecimal addUpHousingLoanInterest = dto.getAddUpHousingLoanInterest();
addUpDeduction.setAddUpHousingLoanInterest(Util.null2String(addUpHousingLoanInterest));
//累计住房租金
BigDecimal addUpHousingRent = dto.getAddUpHousingRent();
addUpDeduction.setAddUpHousingRent(Util.null2String(addUpHousingRent));
//累计赡养老人
BigDecimal addUpSupportElderly = dto.getAddUpSupportElderly();
addUpDeduction.setAddUpSupportElderly(Util.null2String(addUpSupportElderly));
if (errorSum == 0) {
successCount += 1;
// 合格数据
eligibleData.add(addUpDeduction);
} else {
errorCount += 1;
// 添加错误数据
}
}
//入库
addUpDeductionBiz.handleImportData(eligibleData);
apidatas.put("successCount", successCount);
apidatas.put("errorCount", errorCount);
apidatas.put("errorData", errorData);
} finally {
IOUtils.closeQuietly(fileInputStream);
}
return apidatas;
}
private void checkImportParam() {
AddUpDeductionImportParam importParam = (AddUpDeductionImportParam) params.get("importParam");
//excel文件id
String imageId = Util.null2String(importParam.getImageId());
//税款所属期
String declareMonthStr = Util.null2String(importParam.getDeclareMonth());
//个税扣缴义务人
String taxAgentId = Util.null2String(importParam.getTaxAgentId());
if (StringUtils.isBlank(imageId)) {
throw new SalaryRunTimeException("文件不存在");
}
if (StringUtils.isBlank(declareMonthStr)) {
throw new SalaryRunTimeException("税款所属期为空");
}
}
}

View File

@ -1,5 +1,6 @@
package com.engine.salary.entity.datacollection.dto;
import com.engine.salary.util.excel.ExcelProperty;
import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.AllArgsConstructor;
import lombok.Builder;
@ -36,61 +37,73 @@ public class AddUpDeductionListDTO {
/**
* 姓名
*/
@ExcelProperty(index = 0)
private String username;
/**
* 个税扣缴义务人
*/
@ExcelProperty(index = 1)
private String taxAgentName;
/**
* 部门
*/
@ExcelProperty(index = 2)
private String departmentName;
/**
* 手机号
*/
@ExcelProperty(index = 3)
private String mobile;
/**
* 工号
*/
@ExcelProperty(index = 4)
private String jobNum;
/**
* 证件号码
*/
@ExcelProperty(index = 5)
private String idNo;
/**
* 入职日期
*/
@JsonFormat(pattern = "yyyy-MM-dd")
@ExcelProperty(index = 6)
private Date hiredate;
/**
* 累计子女教育
*/
@ExcelProperty(index = 7)
private BigDecimal addUpChildEducation;
/**
* 累计继续教育
*/
@ExcelProperty(index = 8)
private BigDecimal addUpContinuingEducation;
/**
* 累计住房贷款利息
*/
@ExcelProperty(index = 9)
private BigDecimal addUpHousingLoanInterest;
/**
* 累计住房租金
*/
@ExcelProperty(index = 10)
private BigDecimal addUpHousingRent;
/**
* 累计赡养老人
*/
@ExcelProperty(index = 11)
private BigDecimal addUpSupportElderly;
}

View File

@ -0,0 +1,31 @@
package com.engine.salary.entity.datacollection.param;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* 数据采集-累计专项附加扣除查询参数
* <p>Copyright: Copyright (c) 2022</p>
* <p>Company: 泛微软件</p>
*
* @author qiantao
* @version 1.0
**/
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class AddUpDeductionImportParam {
//上传文件id
String imageId;
//税款所属期
String declareMonth;
//个税扣缴义务人
String taxAgentId;
}

View File

@ -82,5 +82,24 @@ public interface AddUpDeductionMapper {
*/
List<AddUpDeductionListDTO> list(@Param("param") AddUpDeductionQueryParam param);
/**
* 根据条件查询
* @param param
* @return
*/
List<AddUpDeduction> listSome(@Param("param") AddUpDeduction param);
/**
* 批量插入
* @param pos
*/
void insertData(@Param("collection") List<AddUpDeduction> pos);
/**
* 批量修改
* @param updateList
*/
void updateData(@Param("collection") List<AddUpDeduction> updateList);
}

View File

@ -269,21 +269,23 @@
<!-- 员工基本信息 -->
<select id="listEmployee" resultType="com.engine.salary.entity.datacollection.DataCollectionEmployee">
select e.ID as employeeId,
e.LASTNAME as username,
select e.ID as employeeId,
e.LASTNAME as username,
d.DEPARTMENTNAME as deparmentName
from hrmresource e
left join hrmdepartment d on e.departmentid = d.id
left join hrmdepartment d on e.departmentid = d.id
where e.status not in (4, 5, 6, 7)
</select>
<!-- E10 sql -->
<!-- E10 sql -->
<sql id="addUpDeductionColumn">
t1.id,
t1
.
id
,
t1.declare_month,
t1.employee_id,
e.lastname as usename,
@ -477,12 +479,13 @@
LEFT JOIN hrmresource e ON e.id = t1.employee_id
LEFT JOIN hrmdepartment d ON d.id = e.departmentid
WHERE
t1.delete_type = 0 AND t2.delete_type = 0
t1.delete_type = 0 AND t2.delete_type = 0
<include refid="paramSql"/>
ORDER BY t1.id DESC
</select>
<select id="list" resultType="com.engine.salary.entity.datacollection.dto.AddUpDeductionListDTO" databaseId="oracle">
<select id="list" resultType="com.engine.salary.entity.datacollection.dto.AddUpDeductionListDTO"
databaseId="oracle">
SELECT
<include refid="addUpDeductionColumn"/>
FROM
@ -491,11 +494,12 @@
LEFT JOIN hrmresource e ON e.id = t1.employee_id
LEFT JOIN hrmdepartment d ON d.id = e.departmentid
WHERE
t1.delete_type = 0 AND t2.delete_type = 0
t1.delete_type = 0 AND t2.delete_type = 0
<include refid="paramSql"/>
ORDER BY t1.id DESC
</select>
<select id="list" resultType="com.engine.salary.entity.datacollection.dto.AddUpDeductionListDTO" databaseId="sqlserver">
<select id="list" resultType="com.engine.salary.entity.datacollection.dto.AddUpDeductionListDTO"
databaseId="sqlserver">
SELECT
<include refid="addUpDeductionColumn"/>
FROM
@ -504,18 +508,174 @@
LEFT JOIN hrmresource e ON e.id = t1.employee_id
LEFT JOIN hrmdepartment d ON d.id = e.departmentid
WHERE
t1.delete_type = 0 AND t2.delete_type = 0
t1.delete_type = 0 AND t2.delete_type = 0
<include refid="paramSql"/>
ORDER BY t1.id DESC
</select>
<select id="listSome" resultMap="BaseResultMap">
SELECT
<include refid="baseColumns"/>
FROM hrsa_add_up_deduction t
WHERE delete_type = 0
<if test="param.declareMonth != null">
and declare_month = #{param.declareMonth}
</if>
</select>
<insert id="insertData">
INSERT INTO hrsa_add_up_deduction(
id,
employee_id,
tax_agent_id,
declare_month,
add_up_child_education,
add_up_continuing_education,
add_up_housing_loan_interest,
add_up_housing_rent,
add_up_support_elderly,
create_time,
update_time,
creator,
tenant_key
)
VALUES
<foreach collection="collection" item="item" separator=",">
(
#{item.id},
#{item.employeeId},
#{item.taxAgentId},
#{item.declareMonth},
#{item.addUpChildEducation},
#{item.addUpContinuingEducation},
#{item.addUpHousingLoanInterest},
#{item.addUpHousingRent},
#{item.addUpSupportElderly},
#{item.createTime},
#{item.updateTime},
#{item.creator},
#{item.tenantKey}
)
</foreach>
</insert>
<insert id="insertData" databaseId="oracle">
INSERT INTO hrsa_add_up_deduction(
id,
employee_id,
tax_agent_id,
declare_month,
add_up_child_education,
add_up_continuing_education,
add_up_housing_loan_interest,
add_up_housing_rent,
add_up_support_elderly,
create_time,
update_time,
creator,
tenant_key
)
<foreach collection="collection" item="item" separator="union all">
select
#{item.id},
#{item.employeeId},
#{item.taxAgentId},
#{item.declareMonth},
#{item.addUpChildEducation},
#{item.addUpContinuingEducation},
#{item.addUpHousingLoanInterest},
#{item.addUpHousingRent},
#{item.addUpSupportElderly},
#{item.createTime},
#{item.updateTime},
#{item.creator},
#{item.tenantKey}
from dual
</foreach>
</insert>
<insert id="insertData" databaseId="sqlserver">
INSERT INTO hrsa_add_up_deduction(
id,
employee_id,
tax_agent_id,
declare_month,
add_up_child_education,
add_up_continuing_education,
add_up_housing_loan_interest,
add_up_housing_rent,
add_up_support_elderly,
create_time,
update_time,
creator,
tenant_key
)
VALUES
<foreach collection="collection" item="item" separator=",">
(
#{item.id},
#{item.employeeId},
#{item.taxAgentId},
#{item.declareMonth},
#{item.addUpChildEducation},
#{item.addUpContinuingEducation},
#{item.addUpHousingLoanInterest},
#{item.addUpHousingRent},
#{item.addUpSupportElderly},
#{item.createTime},
#{item.updateTime},
#{item.creator},
#{item.tenantKey}
)
</foreach>
</insert>
<update id="updateData" parameterType="java.util.List">
update hrsa_add_up_deduction
<trim prefix="set" suffixOverrides=",">
<trim prefix="add_up_child_education =case" suffix="end,">
<foreach collection="collection" item="item" index="index">
<if test="item.addUpChildEducation!=null">
when id=#{item.id} then #{item.addUpChildEducation}
</if>
</foreach>
</trim>
<trim prefix="add_up_continuing_education =case" suffix="end,">
<foreach collection="collection" item="item" index="index">
<if test="item.addUpContinuingEducation!=null">
when id=#{item.id} then #{item.addUpContinuingEducation}
</if>
</foreach>
</trim>
<trim prefix="add_up_housing_loan_interest =case" suffix="end,">
<foreach collection="collection" item="item" index="index">
<if test="item.addUpHousingLoanInterest!=null">
when id=#{item.id} then #{item.addUpHousingLoanInterest}
</if>
</foreach>
</trim>
<trim prefix="add_up_housing_rent =case" suffix="end,">
<foreach collection="collection" item="item" index="index">
<if test="item.addUpHousingRent!=null">
when id=#{item.id} then #{item.addUpHousingRent}
</if>
</foreach>
</trim>
<trim prefix="add_up_support_elderly =case" suffix="end,">
<foreach collection="collection" item="item" index="index">
<if test="item.addUpSupportElderly!=null">
when id=#{item.id} then #{item.addUpSupportElderly}
</if>
</foreach>
</trim>
</trim>
where
id in
<foreach collection="collection" item="item" index="index" separator="," open="(" close=")">
#{item.id}
</foreach>
</update>
</mapper>

View File

@ -11,4 +11,6 @@ public interface AddUpDeductionService {
HSSFWorkbook export(Map<String, Object> params);
Map<String, Object> getSearchCondition(Map<String, Object> params);
Map<String, Object> importAddUpDeduction(Map<String, Object> params);
}

View File

@ -3,6 +3,7 @@ package com.engine.salary.service.impl;
import com.engine.core.impl.Service;
import com.engine.salary.cmd.datacollection.AddUpDeductionExportCmd;
import com.engine.salary.cmd.datacollection.AddUpDeductionGetSearchConditionCmd;
import com.engine.salary.cmd.datacollection.AddUpDeductionImportCmd;
import com.engine.salary.cmd.datacollection.AddUpDeductionListCmd;
import com.engine.salary.service.AddUpDeductionService;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
@ -13,16 +14,21 @@ public class AddUpDeductionServiceImpl extends Service implements AddUpDeduction
@Override
public Map<String, Object> list(Map<String, Object> params) {
return commandExecutor.execute(new AddUpDeductionListCmd(params,user));
return commandExecutor.execute(new AddUpDeductionListCmd(params, user));
}
@Override
public HSSFWorkbook export(Map<String, Object> params) {
return commandExecutor.execute(new AddUpDeductionExportCmd(params,user));
return commandExecutor.execute(new AddUpDeductionExportCmd(params, user));
}
@Override
public Map<String, Object> getSearchCondition(Map<String, Object> params) {
return commandExecutor.execute(new AddUpDeductionGetSearchConditionCmd(params,user));
return commandExecutor.execute(new AddUpDeductionGetSearchConditionCmd(params, user));
}
@Override
public Map<String, Object> importAddUpDeduction(Map<String, Object> params) {
return commandExecutor.execute(new AddUpDeductionImportCmd(params, user));
}
}

View File

@ -6,6 +6,7 @@ import org.apache.commons.lang3.exception.ContextedRuntimeException;
import org.apache.poi.ss.usermodel.Sheet;
import org.springframework.web.multipart.MultipartFile;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.util.ArrayList;
@ -47,6 +48,27 @@ public class ExcelParseHelper {
return list;
}
/**
* Excel 解析为 JavaBean 对象
*
* @param file excel文件
* @param clazz 解析bean的类
* @param sheetIndex excel中第几个sheet从0开始
* @param rowIndex 从第几行开始解析,第一行是0
* @param standardCellNum 模板验证该sheet应有多少列
* @param fileName 文件名
* @return
*/
public static <T> List<T> parse(InputStream file, Class<T> clazz, int sheetIndex, int rowIndex, int standardCellNum, String fileName) {
List<List<String>> result = parse(file, sheetIndex, rowIndex, standardCellNum, fileName);
List<T> list = new ArrayList<T>();
for (List<String> rowDatas : result) {
T t = setField(clazz, rowDatas);
list.add(t);
}
return list;
}
/**
* <strong>获取excel数据</strong>
*
@ -73,6 +95,32 @@ public class ExcelParseHelper {
return result;
}
/**
* <strong>获取excel数据</strong>
*
* @param file 文件
* @param sheetIndex 解析第几个sheet
* @param rowIndex 从第几行开始解析第一行为 0依次类推
* @return 二维数据集合
*/
private static List<List<String>> parse(InputStream file, int sheetIndex, int rowIndex, int standardCellNum, String fileName) {
Sheet sheet = ExcelSupport.parseFile(file, sheetIndex, fileName);
int rowCount = sheet.getPhysicalNumberOfRows(); // 总行数
int cellCount = sheet.getRow(PARSE_EXCEL_ROW_VALID_CELL_INDEX).getPhysicalNumberOfCells(); // 总列数
Validate.isTrue(standardCellNum == cellCount, "Error in excel template! Page %s sheet should have %s column data, existing in %s column , please check the template!", sheetIndex, standardCellNum, cellCount);
List<List<String>> result = new ArrayList<List<String>>();
for (; rowIndex < rowCount; rowIndex++) {
List<String> cellResult = new ArrayList<String>();
for (int j = 0; j < cellCount; j++) {
cellResult.add(ExcelSupport.getCellValue(sheet, rowIndex, j));
}
result.add(cellResult);
}
return result;
}
/**
* 为对象的每一个属性赋值
*

View File

@ -2,16 +2,20 @@ package com.engine.salary.util.excel;
import org.apache.commons.lang3.Validate;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.DateUtil;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.multipart.MultipartFile;
import java.io.BufferedInputStream;
import java.io.InputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import static org.apache.poi.ss.usermodel.CellType.*;
import static org.apache.poi.ss.usermodel.CellType.STRING;
public class ExcelSupport {
@ -22,6 +26,7 @@ public class ExcelSupport {
private static final String EXCEL_TYPE_XLSX = "xlsx";
private static final String EXCEL_TYPE_XLS = "xls";
/**
* 解析文件获取单个sheet
*
@ -46,6 +51,28 @@ public class ExcelSupport {
}
}
/**
* 解析文件获取单个sheet
*
* @param sheetIndex sheet下标从0开始
* @return sheet
*/
public static Sheet parseFile(InputStream ins, int sheetIndex,String fileName) {
Workbook workBook = null;
try {
if (fileName.endsWith(EXCEL_TYPE_XLSX)) {
workBook = new XSSFWorkbook(new BufferedInputStream(ins));
} else if (fileName.endsWith(EXCEL_TYPE_XLS)) {
workBook = new HSSFWorkbook(new BufferedInputStream(ins));
} else {
throw new IllegalArgumentException("File format error! Only xlsx and xls types are supported");
}
return workBook.getSheetAt(sheetIndex);
} catch (Exception e) {
throw new IllegalArgumentException(e);
}
}
/**
* 返回指定单元格的数据
*

View File

@ -2,6 +2,7 @@ package com.engine.salary.web;
import com.engine.common.util.ParamUtil;
import com.engine.common.util.ServiceUtil;
import com.engine.salary.entity.datacollection.param.AddUpDeductionImportParam;
import com.engine.salary.entity.datacollection.param.AddUpDeductionQueryParam;
import com.engine.salary.service.AddUpDeductionService;
import com.engine.salary.service.impl.AddUpDeductionServiceImpl;
@ -14,14 +15,15 @@ import weaver.hrm.User;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.*;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.StreamingOutput;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Map;
@ -34,6 +36,7 @@ public class AddUpDeductionController {
/**
* 数据采集-累计专项附加扣除列表的高级搜索
*
* @return
*/
@GET
@ -106,17 +109,26 @@ public class AddUpDeductionController {
e.printStackTrace();
}
StreamingOutput output = new StreamingOutput() {
@Override
public void write(OutputStream outputStream) throws IOException, WebApplicationException {
workbook.write(outputStream);
outputStream.flush();
}
StreamingOutput output = outputStream -> {
workbook.write(outputStream);
outputStream.flush();
};
response.setContentType("application/octet-stream");
return Response.ok(output)
.header("Content-disposition", "attachment;filename=" + fileName)
.header("Cache-Control", "no-cache").build();
}
//新建个税扣缴义务人
@POST
@Path("/importAddUpDeduction")
@Produces(MediaType.APPLICATION_JSON)
public String importAddUpDeduction(@Context HttpServletRequest request, @Context HttpServletResponse response, @RequestBody AddUpDeductionImportParam importParam) {
User user = HrmUserVarify.getUser(request, response);
Map<String, Object> map = ParamUtil.request2Map(request);
map.put("importParam", importParam);
return ResponseResult.run(getService(user)::importAddUpDeduction, map);
}
}