1.配置文件 :PurchaseConfig.java
package com.chinalife.excel.config;
import java.util.HashMap;
import java.util.Map;
public class PurchaseConfig {
public static Map<String, String> purchaseName = new HashMap<String, String>();
static {
/*合同新签*/
purchaseName.put("名称(一类名称)","name");//
purchaseName.put("模块及配件名称(二类名称)","modelName");//
purchaseName.put("品牌","brand");//
purchaseName.put("型号","kind");//
purchaseName.put("序列号","series");//
purchaseName.put("规格描述","norm");//
purchaseName.put("服务","service");//
purchaseName.put("数量","quantity");//
purchaseName.put("单价","unitPrice");//
purchaseName.put("合计金额","totalAmount");//
purchaseName.put("备注","description");//
}
}
2.工具类:ExcelUtil.java
package com.chinalife.excel.util;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import com.chinalife.excel.config.PurchaseConfig;
public class ExcelUtil {
Log log4j;
/**
* 读取 office 2003 excel
* @author WangKai
* @param String filePath="c:/1.xls";
* @throws IOException
* @throws FileNotFoundException
*/
public List<String> read2003Excel(File file)
throws IOException {
List<String> list = new ArrayList<String>();
try {
HSSFWorkbook hwb = new HSSFWorkbook(new FileInputStream(file));
HSSFSheet sheet = hwb.getSheetAt(0);
Object value = null;
HSSFRow row = null;
HSSFCell cell = null;
System.out.println("读取office 2003 excel内容如下:");
for (int i = sheet.getFirstRowNum(); i <= sheet.getPhysicalNumberOfRows(); i++) {
row = sheet.getRow(i);
if (row == null) {
continue;
}
String temp="";//记录对象变量顺序
List<Object> linked = new LinkedList<Object>();
for (int j = 0; j < row.getLastCellNum(); j++) {
cell = row.getCell(j);
if (null == cell) {
value="";
}else{
DecimalFormat df = new DecimalFormat("0");// 格式化 number String
// 字符
SimpleDateFormat sdf = new SimpleDateFormat(
"yyyy-MM-dd HH:mm:ss");// 格式化日期字符串
DecimalFormat nf = new DecimalFormat("0");// 格式化数字
switch (cell.getCellType()) {
case HSSFCell.CELL_TYPE_FORMULA:
try {
value = String.valueOf(cell.getStringCellValue());
} catch (IllegalStateException e) {
value = String.valueOf(df.format(cell.getNumericCellValue()));
}
break;
case XSSFCell.CELL_TYPE_STRING:
// System.out.println(i + "行" + j + " 列 is String type");
value = cell.getStringCellValue();
//System.out.print(" " + value + " ");
break;
case XSSFCell.CELL_TYPE_NUMERIC:
// System.out.println(i + "行" + j
// + " 列 is Number type ; DateFormt:"
// + cell.getCellStyle().getDataFormatString());
if ("@".equals(cell.getCellStyle().getDataFormatString())) {
value = df.format(cell.getNumericCellValue());
} else if ("General".equals(cell.getCellStyle()
.getDataFormatString())) {
value = nf.format(cell.getNumericCellValue());
} else {
value = sdf.format(HSSFDateUtil.getJavaDate(cell
.getNumericCellValue()));
}
//System.out.print(" " + value + " ");
break;
case XSSFCell.CELL_TYPE_BOOLEAN:
// System.out.println(i + "行" + j + " 列 is Boolean type");
value = cell.getBooleanCellValue();
//System.out.print(" " + value + " ");
break;
case XSSFCell.CELL_TYPE_BLANK:
// System.out.println(i + "行" + j + " 列 is Blank type");
value = "";
//System.out.print(" " + value + " ");
break;
default:
// System.out.println(i + "行" + j + " 列 is default type");
value = cell.toString();
//System.out.print(" " + value + " ");
}
}
if (null == value || "".equals(value)) {
temp+=""+",";
}else {
temp+=value+",";
}
}
if(StringUtils.isNotBlank(temp)){
System.out.println(temp.substring(0, temp.length()-1));
list.add(temp.substring(0, temp.length()-1));
}
}
} catch (Exception e) {
e.printStackTrace();
log4j.error("ExcelUtil:read2003Excel:读取 office 2003 excel失败", e);
}
return list;
}
/**
* 读取Office 2007 excel
* @author WangKai
* @param String filePath="c:/1.xlsx";
*/
public List<String> read2007Excel(File file) {
List templete=new ArrayList();
try {
XSSFWorkbook xwb = new XSSFWorkbook(new FileInputStream(file));
// 读取第一章表格内容
XSSFSheet sheet = xwb.getSheetAt(0);
Object value = null;
XSSFRow row = null;
XSSFCell cell = null;
System.out.println("读取office 2007 excel内容如下:");
for (int i = sheet.getFirstRowNum(); i <= sheet.getPhysicalNumberOfRows(); i++) {
row = sheet.getRow(i);
if (row == null) {
continue;
}
String temp="";//记录对象变量顺序
for (short j = row.getFirstCellNum(); j < row.getLastCellNum(); j++) {
//System.out.println(row.getLastCellNum());
if(row.getFirstCellNum()==-1){
break;
}else {
cell = row.getCell(j);
if (null == cell) {
value="";
}else{
DecimalFormat df = new DecimalFormat("0");// 格式化 number String
// 字符
SimpleDateFormat sdf = new SimpleDateFormat(
"yyyy-MM-dd HH:mm:ss");// 格式化日期字符串
DecimalFormat nf = new DecimalFormat("0");// 格式化数字
switch (cell.getCellType()) {
case HSSFCell.CELL_TYPE_FORMULA:
try {
value = String.valueOf(cell.getStringCellValue());
} catch (IllegalStateException e) {
value = String.valueOf(df.format(cell.getNumericCellValue()));
}
break;
case XSSFCell.CELL_TYPE_STRING:
// System.out.println(i + "行" + j + " 列 is String type");
value = cell.getStringCellValue();
//System.out.print(" " + value + " ");
break;
case XSSFCell.CELL_TYPE_NUMERIC:
// System.out.println(i + "行" + j
// + " 列 is Number type ; DateFormt:"
// + cell.getCellStyle().getDataFormatString());
if ("@".equals(cell.getCellStyle().getDataFormatString())) {
value = df.format(cell.getNumericCellValue());
} else if ("General".equals(cell.getCellStyle()
.getDataFormatString())) {
value = nf.format(cell.getNumericCellValue());
} else {
value = sdf.format(HSSFDateUtil.getJavaDate(cell
.getNumericCellValue()));
}
//System.out.print(" " + value + " ");
break;
case XSSFCell.CELL_TYPE_BOOLEAN:
// System.out.println(i + "行" + j + " 列 is Boolean type");
value = cell.getBooleanCellValue();
//System.out.print(" " + value + " ");
break;
case XSSFCell.CELL_TYPE_BLANK:
// System.out.println(i + "行" + j + " 列 is Blank type");
value = "";
// System.out.println(value);
break;
default:
// System.out.println(i + "行" + j + " 列 is default type");
value = cell.toString();
//System.out.print(" " + value + " ");
}
}
if (null== value || "".equals(value)) {
temp+=""+",";
}else {
temp+=value+",";
}
}
}
if(StringUtils.isNotBlank(temp)){
System.out.println(temp);
templete.add(temp.substring(0, temp.length()-1));
}
}
System.out.println();
} catch (Exception e) {
e.printStackTrace();
log4j.error("ExcelUtil:read2007Excel:读取2007Excel失败", e);
}
return templete;
}
//将对象赋值
/**@detail 前面是变量,后面是变量对应的n组参数值
* @param temp =["a,,b,c,,","1,2,3,4,5,6","1,2,3,4,5,6"]
*
*
* */
public List<String> chooseValue(List<String> temp){
List<String> objectList=new ArrayList<String> ();
try {
if(temp!=null){
if(temp.size()>1){
//首先读取标题,将中文转化成对应变量
String[] str=temp.get(0).toString().split(",");
String temStr="";
//计数器:专门标记配置文件没有获取变量的参数
String noValue="";
for(int i=0;i<str.length;i++){
String isStr=new PurchaseConfig().purchaseName.get(str[i]);
if(StringUtils.isNotBlank(isStr)){
temStr+=isStr+",";
}else{
noValue+=",";
}
}
temStr=this.delLastComma(temStr);
if(StringUtils.isNotBlank(temStr)){
objectList.add(temStr);
}
//如果计数器noValue不为空,有变量没有值
noValue=this.delLastComma(noValue);
//清空将中文名对应英文对象且去除其标识,留下对应的对象list
str=null;
temp.remove(0);
for (int i=0;i<temp.size();i++){
//转化成以","隔开的字符串reStr
String [] t=temp.get(i).toString().split(",");
String reStr="";
//左位移一位
if(StringUtils.isNotBlank(noValue)){
String []noValues=noValue.split(",");
for(int j=0;j<t.length;j++){
for(int z=0;z<noValues.length;z++){
int integer=Integer.parseInt(noValues[z]);
if(j!=integer){
if(StringUtils.isBlank(t[j])){
reStr+=""+",";
}else{
reStr+=t[j]+",";
}
}
}
}
//去掉末位的",",放入list
reStr=this.delLastComma(reStr);
if(StringUtils.isNotBlank(reStr)){
objectList.add(reStr);
}
}else{
objectList.add(temp.get(i).toString());
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
log4j.error("ExcelUtil:chooseValue:变量与参数对应失败!", e);
}
return objectList;
}
/**
* 调用set方法把值set到对象当中
* @param obj 指定对象
* @param clazz 对象的class
* @param name 变量名称
* @param typeClass field的类型的class
* @param value 对应的值
*/
public Object setValue(Object o,String name, String param){
try {
Class<?> clazz = o.getClass();
Field[] fields = clazz.getDeclaredFields();
String []names=name.split(",");
//临时变量,参数值<=变量名长度(防止数组越界)
String []temStr=new String[names.length];
String []params=param.split(",");
if(temStr.length>params.length){
for(int i=0;i<params.length;i++){
temStr[i]=params[i];
}
}else{
for(int i=0;i<temStr.length;i++){
temStr[i]=params[i];
}
}
for(int i=0;i<names.length;i++){
String methodName = "set" + names[i].substring(0, 1).toUpperCase() + names[i].substring(1);
for(Field field : fields){
Class<?> typeClass = field.getType();
if(StringUtils.isNotBlank(field.getName())){
if(field.getName().equals(names[i])){
Method method = clazz.getDeclaredMethod(methodName, new Class[]{typeClass});
method.invoke(o, new Object[]{getClassTypeValue(typeClass, temStr[i])});
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
log4j.error("ExcelUtil:setValue:反射失败!调用set方法把值set到对象当中 ",e);
}
return o;
}
/**
* 通过class类型获取获取对应类型的值
* @param typeClass class类型
* @param value 值
* @return Object
*/
private Object getClassTypeValue(Class<?> typeClass, String value){
try {
if(typeClass == int.class){
if(StringUtils.isBlank(value)){
return 0;
}
return Integer.parseInt(value);
}else if(typeClass == short.class){
if(StringUtils.isBlank(value)){
return 0;
}
return Short.parseShort(value);
}else if(typeClass == byte.class){
if(StringUtils.isBlank(value)){
return 0;
}
return Byte.parseByte(value);
}else if(typeClass == double.class){
if(StringUtils.isBlank(value)){
return 0;
}
return Double.parseDouble(value);
}else if(typeClass == boolean.class){
if(StringUtils.isBlank(value)){
return false;
}
return Boolean.parseBoolean(value);
}else if(typeClass == float.class){
if(StringUtils.isBlank(value)){
return 0;
}
return Float.parseFloat(value);
}else if(typeClass == long.class){
if(StringUtils.isBlank(value)){
return 0;
}
return Long.parseLong(value);
}else if(typeClass == Integer.class){
if(StringUtils.isBlank(value)){
return null;
}
return (int)Double.parseDouble(value);
}else if(typeClass == String.class){
if(StringUtils.isBlank(value)){
return "";
}
return value;
}else {
return typeClass.cast(value);
}
} catch (Exception e) {
e.printStackTrace();
log4j.error("ExcelUtil:getClassTypeValue:通过class类型获取获取对应类型的值失败! ",e);
}
return typeClass.cast(value);
}
//去掉末尾","
public String delLastComma(String reStr){
try {
//去掉末位的",",放入list
if(reStr.length()>1){
if(reStr.substring(reStr.length()-1).equals(",")){
reStr=reStr.substring(0, reStr.length()-1);
}
}
} catch (Exception e) {
e.printStackTrace();
log4j.error("ExcelUtil:delLastComma:去掉末尾失败! ",e);
}
return reStr;
}
}
3.服务方法:ExcelInBaseDataServiceImpl.java
package com.chinalife.excel.service;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.Resource;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.springframework.stereotype.Repository;
import com.chinalife.contract.contractnew.dao.IHardContractInfoDao;
import com.chinalife.contract.contractnew.dao.IHardPurchaseInfoDao;
import com.chinalife.contract.contractnew.dao.IOfficeContractInfoDao;
import com.chinalife.contract.contractnew.dao.IOfficePurchaseInfoDao;
import com.chinalife.contract.contractnew.dao.ISoftContractInfoDao;
import com.chinalife.contract.contractnew.dao.ISoftPurchaseInfoDao;
import com.chinalife.contract.contractnewsign.dao.IContractInfoDao;
import com.chinalife.contract.po.ContractInfo;
import com.chinalife.contract.po.HardContractInfo;
import com.chinalife.contract.po.HardPurchaseInfo;
import com.chinalife.contract.po.OfficeContractInfo;
import com.chinalife.contract.po.OfficePurchaseInfo;
import com.chinalife.contract.po.SoftContractInfo;
import com.chinalife.contract.po.SoftPurchaseInfo;
import com.chinalife.contract.vo.UserVoInfo;
import com.chinalife.excel.util.ExcelUtil;
import com.chinalife.util.Entity;
@Repository("excelInBaseDataServiceImpl")
public class ExcelInBaseDataServiceImpl implements IExcelInBaseDataService{
@Resource(name="contractInfoDaoImpl")
private IContractInfoDao contractInfoDaoImpl;
@Resource(name="officePurchaseInfoDao")
public IOfficePurchaseInfoDao officePurchaseInfoDao;
@Resource(name="officeContractInfoDao")
public IOfficeContractInfoDao officeContractInfoDao;
@Resource(name="hardPurchaseInfoDao")
public IHardPurchaseInfoDao hardPurchaseInfoDao;
@Resource(name="hardContractInfoDao")
public IHardContractInfoDao hardContractInfoDao;
@Resource(name="softPurchaseInfoDao")
public ISoftPurchaseInfoDao softPurchaseInfoDao;
@Resource(name="softContractInfoDao")
public ISoftContractInfoDao softContractInfoDao;
Log log4j;
/**
* @author WangKai
* @param file 文件
* @param fielType xlsx 或者 xls类型
* @param id 合同流水号
* @return String
* */
public String saveExcelToBase(File file,String fileType,String id,String user ){
try {
if(!file.exists()){
return null;
//log4j.error("ExcelInBaseDataServiceImpl:saveExcelToBase:路径不存在! ");
}
if(StringUtils.isBlank(id)){
return null;
//log4j.error("ExcelInBaseDataServiceImpl:saveExcelToBase:合同流水号不存在! ");
}else if(StringUtils.isBlank(fileType)){
return null;
//log4j.error("ExcelInBaseDataServiceImpl:saveExcelToBase:路径不存在! ");
}else if(StringUtils.isBlank(user)){
return null;
//log4j.error("ExcelInBaseDataServiceImpl:saveExcelToBase:该用户不存在(合同类型必填项)! ");
}
ExcelUtil excelUtil=new ExcelUtil();
List objList =new ArrayList();
Object o=null;
//filePath="c:/2.xlsx";
List s=new ArrayList();
if (fileType.equals("xlsx")) {
s=excelUtil.read2007Excel(file);
}else if(fileType.equals("xls")) {
s=excelUtil.read2003Excel(file);
}else {
//log4j.error("ExcelInBaseDataServiceImpl:saveExcelToBase:文件类型不正确! ");
return null;
}
ContractInfo c=new ContractInfo();
c=contractInfoDaoImpl.queryById(id);//查询合同二级类型
if(StringUtils.isBlank(c.getC_second_type())&&StringUtils.isBlank(c.getC_first_type())){
return null;
}
List list=excelUtil.chooseValue(s);//优化变量与参数
//获取采购类objList对象
if(list != null && list.size()>1){
String valueName=list.get(0).toString();
list.remove(0);
for(int i=0;i<list.size();i++){
if(list.get(i)!=null){
if(c!=null){
//初始化对象
if(StringUtils.isNotBlank(c.getC_second_type())){
if(c.getC_second_type().equals("00050001")){//办公室采购类
o=new OfficePurchaseInfo();
}else if(c.getC_second_type().equals("00060001")){//IT硬件采购类
o=new HardPurchaseInfo();
}else if(c.getC_second_type().equals("00070001")){//IT软件采购类
o=new SoftPurchaseInfo();
}
}else{
return null;
}
}
o= excelUtil.setValue(o,valueName,list.get(i).toString());//反射方法依次赋值
if(o!=null){
objList.add(o);
}
}
}
}
//采购类list依次保存
if(objList!=null){
String oneTypeId="";
if(c.getC_first_type().equals("0005")){//办公室采购合同
OfficeContractInfo infor =new OfficeContractInfo();
infor.setC_id(id);
infor.setInDate(Entity.getDateTime());//获取当前操作的时间 设置入机时间
infor.setModifyDate(Entity.getDateTime());//设置修改时间
infor.setOperator(user);//操作人
oneTypeId=officeContractInfoDao.save(infor);
}else if(c.getC_first_type().equals("0006")){//IT硬件采购合同
HardContractInfo infor =new HardContractInfo();
infor.setC_id(id);
infor.setInDate(Entity.getDateTime());//获取当前操作的时间 设置入机时间
infor.setModifyDate(Entity.getDateTime());//设置修改时间
infor.setOperator(user);//操作人
oneTypeId=hardContractInfoDao.save(infor);
}else if(c.getC_first_type().equals("0007")){//IT软件采购合同
SoftContractInfo infor =new SoftContractInfo();
infor.setC_id(id);
infor.setInDate(Entity.getDateTime());//获取当前操作的时间 设置入机时间
infor.setModifyDate(Entity.getDateTime());//设置修改时间
infor.setOperator(user);//操作人
oneTypeId=softContractInfoDao.save(infor);
}
if(StringUtils.isBlank(oneTypeId)){
//log4j.error("合同一级类型流水号生成失败!");
return null;
}
for (int i=0;i<objList.size();i++){
//初始化对象
if(StringUtils.isNotBlank(c.getC_second_type())){
if(c.getC_second_type().equals("00050001")){//办公室采购类
OfficePurchaseInfo info=new OfficePurchaseInfo();
info=(OfficePurchaseInfo) objList.get(i);
if(info!=null){
info.setC_id(id);
info.setInDate(Entity.getDateTime());//获取当前操作的时间 设置入机时间
info.setModifyDate(Entity.getDateTime());//设置修改时间
info.setOperator(user);//操作人
info.setOfficeContractInfoId(oneTypeId);
}
officePurchaseInfoDao.save(info);
}else if(c.getC_second_type().equals("00060001")){//IT硬件采购类
HardPurchaseInfo info=new HardPurchaseInfo();
info=(HardPurchaseInfo) objList.get(i);
if(info!=null){
info.setC_id(id);
info.setInDate(Entity.getDateTime());//获取当前操作的时间 设置入机时间
info.setModifyDate(Entity.getDateTime());//设置修改时间
info.setOperator(user);//操作人
info.setHardContractInfoId(oneTypeId);
}
hardPurchaseInfoDao.save(info);
}else if(c.getC_second_type().equals("00070001")){//IT软件采购类
SoftPurchaseInfo info=new SoftPurchaseInfo();
info=(SoftPurchaseInfo) objList.get(i);
if(info!=null){
info.setC_id(id);
info.setInDate(Entity.getDateTime());//获取当前操作的时间 设置入机时间
info.setModifyDate(Entity.getDateTime());//设置修改时间
info.setOperator(user);//操作人
info.setSoftContractInfoId(oneTypeId);
}
softPurchaseInfoDao.save(info);
}
}else{
return null;
}
}
}
System.out.println(objList);
} catch (Exception e) {
e.printStackTrace();
log4j.error("ExcelInBaseDataServiceImpl:saveExcelToBase:保存excel到数据库失败! ",e);
}
return null;
}
public static void main(String[] args) {
String s="a,,b,,";
String []ss=s.split(",");
System.out.println(ss);
}
}
4.接口:IExcelInBaseDataService.java
package com.chinalife.excel.service;
import java.io.File;
public interface IExcelInBaseDataService {
/**
* @author WangKai
* @param filePath "c:/1.xlsx"
* @param id 合同流水号
* @return String
* */
public String saveExcelToBase(File filePath,String fileType,String id,String user);
}
Excel 内容