pom.依赖
<!--poi-->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.17</version>
</dependency>
导入工具类
package com.zsCat.common.utils;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFDataFormat;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class ParseExcelUtils {
public static List<String[]> rosolveFile(InputStream is, String suffix,
int startRow) throws IOException, FileNotFoundException {
Workbook xssfWorkbook = null;
if ("xls".equals(suffix)) {
xssfWorkbook = new HSSFWorkbook(is);
} else if ("xlsx".equals(suffix)) {
xssfWorkbook = new XSSFWorkbook(is);
}
Sheet xssfSheet = xssfWorkbook.getSheetAt(0);
if (xssfSheet == null) {
return null;
}
ArrayList<String[]> list = new ArrayList<String[]>();
int lastRowNum = xssfSheet.getLastRowNum();
for (int rowNum = startRow; rowNum <= lastRowNum; rowNum++) {
if (xssfSheet.getRow(rowNum) != null) {
Row xssfRow = xssfSheet.getRow(rowNum);
short firstCellNum = xssfRow.getFirstCellNum();
short lastCellNum = xssfRow.getLastCellNum();
if (firstCellNum != lastCellNum) {
String[] values = new String[lastCellNum];
for (int cellNum = firstCellNum; cellNum < lastCellNum; cellNum++) {
Cell xssfCell = xssfRow.getCell(cellNum);
if (xssfCell == null) {
values[cellNum] = "";
} else {
values[cellNum] = parseExcel(xssfCell);
}
}
list.add(values);
}
}
}
return list;
}
public static String parseExcel(Cell cell) {
DecimalFormat decimalFormat = new DecimalFormat("#.##");
String result = new String();
switch (cell.getCellType()) {
case HSSFCell.CELL_TYPE_NUMERIC:// 数字类型
if (HSSFDateUtil.isCellDateFormatted(cell)) {// 处理日期格式、时间格式
SimpleDateFormat sdf = null;
if (cell.getCellStyle().getDataFormat() == HSSFDataFormat
.getBuiltinFormat("h:mm")) {
sdf = new SimpleDateFormat("HH:mm");
} else {// 日期
sdf = new SimpleDateFormat("yyyy-MM-dd");
}
Date date = cell.getDateCellValue();
result = sdf.format(date);
} else if (cell.getCellStyle().getDataFormat() == 58) {
// 处理自定义日期格式:m月d日(通过判断单元格的格式id解决,id的值是58)
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
double value = cell.getNumericCellValue();
Date date = org.apache.poi.ss.usermodel.DateUtil
.getJavaDate(value);
result = sdf.format(date);
} else {
double value = cell.getNumericCellValue();
CellStyle style = cell.getCellStyle();
DecimalFormat format = new DecimalFormat();
String temp = style.getDataFormatString();
// 单元格设置成常规
if (temp.equals("General")) {
format.applyPattern("#");
}
result = decimalFormat.format((cell.getNumericCellValue()));
}
break;
case HSSFCell.CELL_TYPE_STRING:// String类型
result = cell.getRichStringCellValue().toString();
break;
case HSSFCell.CELL_TYPE_BLANK:
result = "";
default:
result = "";
break;
}
return result;
}
}
模板验证工具类
package com.zscat.shop.utils;
public class ExcleTempletValidateUtils {
/**验证导入的excle数据的表头与模板数据是否相等
*
* @param incomingDataArray 导入的excle数据
* @param excleTemplet 验证模板数组
* @return
*/
public static boolean toExcleValidate(String[] incomingDataArray,String[] excleTemplet){
if(incomingDataArray==null||excleTemplet==null){
return false;
}
if(incomingDataArray.length!=excleTemplet.length&&incomingDataArray.length<1&&excleTemplet.length<1){
return false;
}
for(int i=0;i<incomingDataArray.length;i++){
if(!incomingDataArray[i].equals(excleTemplet[i])){
return false;
}
}
return true;
}
}
导入方法
//导入Excel
@ResponseBody
@PostMapping("/parseExcel")
public R parseExcel(MultipartFile file) {
int tempNum=0;
int length=0;
try {
String fileName = file.getOriginalFilename();
String prefix = fileName.substring(fileName.lastIndexOf(".") + 1);
List<String[]> list = ParseExcelUtils.rosolveFile(file.getInputStream(), prefix, 1); //获取每行的数据
List<String[]> listValidete = ParseExcelUtils.rosolveFile(file.getInputStream(), prefix, 0); //获取每行的数据
length=list.size();
if(listValidete!=null&&listValidete.size()>0){
String[] strValidateClus=listValidete.get(0);
String[] excleTemplet={"机构名称","报价日期","供应商名称","sku编号","sku名称","品牌","单位","规格","税率","无税价","含税价","销售价"};
if (!ExcleTempletValidateUtils.toExcleValidate(strValidateClus,excleTemplet)) {
return R.error("导入数据的模板错误");
}
}
if(length<1){
return R.error("导入数据为空");
}
int num = 0;
List<SupplierQuotationsExcleInpotVo> goodsExcleInpotVoList = new ArrayList<SupplierQuotationsExcleInpotVo>();//商品模板实体集合
List<String> skuNoList = new ArrayList<String>(); //SKU编码集合
for (int i = 0; i < list.size(); i++) {
String[] arr = list.get(i);
if (arr.length < 12) {
return R.error("第" + (i + 2) + "条数据的没有填写完善或着可能是空行");
}
String deptName = arr[0].trim();//机构名称
String offerDate = arr[1].trim();//报价日期
String supplierName = arr[2].trim();//供应商名称
String skuNo = arr[3].trim();//sku编号
String goodsName= arr[4].trim();//sku名称
String brand = arr[5].trim();//品牌
String unit = arr[6].trim();//单位
String goodsSpec = arr[7].trim();//规格
String taxRate = arr[8].trim();//税率
String taxFreePrice = arr[9].trim();//无税价
String freePrice = arr[10].trim();//采购价(含税)
String salePrice = arr[11].trim();//销售价(含税)
if(skuNo==null||skuNo.equals("")){
return R.error("第"+(i+1)+"条数据的【sku编码】未填写");
}
if(deptName==null||deptName.equals("")){
return R.error("sku编码为【"+skuNo+"】的【机构名称】未填写");
}
if(goodsName==null||goodsName.equals("")){
return R.error("sku编码为【"+skuNo+"】的【商品名称】未填写");
}
if(supplierName==null||supplierName.equals("")){
return R.error("sku编码为【"+skuNo+"】的【供应商】未填写");
}
if(brand==null||brand.equals("")){
return R.error("sku编码为【"+skuNo+"】的【品牌】未填写");
}
if(unit==null||unit.equals("")){
return R.error("sku编码为【"+skuNo+"】的【单位】未填写");
}
if(taxRate==null||taxRate.equals("")){
return R.error("sku编码为【"+skuNo+"】的【税率】未填写");
}
Map<String,Object> map=new HashMap<>();
map.put("deptName",deptName);
map.put("type","供应链公司");
SupplierQuotationsExcleInpotVo vo=new SupplierQuotationsExcleInpotVo();//实体
List<DeptDO> dds=deptService.list(map);
if(dds!=null&&dds.size()>0){
vo.setDeptName(deptName);
vo.setDeptNo(dds.get(0).getDeptNo());
dds=null;
}else {
dds=null;
return R.error("机构名称不对,"+deptName+"机构属性为供应链公司");
}
if(offerDate!=null&&offerDate!=""){
Date date = null;
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
try{
vo.setOfferDate(df.parse(offerDate));
}catch (ParseException e){
return R.error("时间格式错误,应该格式为‘2018-08-08’");
}
}else{
return R.error("sku编码为【"+skuNo+"】的报价日期未填写");
}
map.clear();
map.put("supplier",supplierName);
List<SupplierDirectoryDO> ss=supplierDirectoryService.list(map);
if(ss!=null&&ss.size()>0){
vo.setSupplierName(supplierName);
vo.setSupplierNo(ss.get(0).getSupplierNo()+"");
}else {
ss=null;
return R.error(supplierName+":供应商不存在");
}
//新添加验证
SupplierDirectoryDO so =supplierDirectoryService.get(ss.get(0).getSupplierNo().intValue());
ss=null;
List<String> listtt=new ArrayList<>();
if(so.getServeCity()!=null&&!"".equals(so.getServeCity())){
if(so.getServeCity().indexOf(",")!=-1){
String[] s=so.getServeCity().split(",");
for(int p=0;p<s.length;p++){
listtt.add(s[p].trim());
}
}else {
listtt.add(so.getServeCity().trim());
}
}else{
return R.error(supplierName+":没有城市属性");
}
List<String> lists=new ArrayList<>();
if(listtt.size()>0){
for(String ll:listtt){
lists.add(areaService.getlistNoByListName(ll));
}
}
Map<String,Object> params=new HashMap<>();
params.put("cityNos",lists);
List<SupplierQuotationsDetailedDO> supplierQuotationsDetailedList = supplierQuotationsDetailedService.listsku(params);
SkuDO sdo=skuService.findSkuBySkuNo(skuNo);
if(sdo!=null){
if(supplierQuotationsDetailedList!=null&&supplierQuotationsDetailedList.size()>0){
for (SupplierQuotationsDetailedDO sdodd:supplierQuotationsDetailedList){
if(sdodd.getSkuNo().equals(sdo.getSkuNo())){
vo.setSkuNo(skuNo);
vo.setGoodsName(goodsName);
vo.setGoodsSpec(goodsSpec);
}
}
}
}else {
sdo=null;
return R.error("编号为:【"+skuNo+"】的sku,没有分配此【供应商服务的城市】");
}
if(vo.getSkuNo()==null||"".equals(vo.getSkuNo())){
return R.error("编号为:【"+skuNo+"】的sku,不存在,或者没有分配【供应商服务的城市】");
}
map.clear();
map.put("brand",brand);
List<BrandDirectoryDO> bs=brandDirectoryService.list(map);
if(bs!=null&&bs.size()>0){
vo.setBrand(brand);
vo.setBrandNo(bs.get(0).getBrandNo()+"");
bs=null;
}else{
bs=null;
return R.error("【"+brand+"】的品牌,不存在");
}
map.clear();
map.put("unit",unit);
List<UnitDirectoryDO> us=unitDirectoryService.list(map);
if(us!=null&&us.size()>0){
vo.setUnit(unit);
}
if(taxFreePrice!=null&&taxFreePrice!=""&&freePrice!=null&&freePrice!=""){
return R.error("编号为:【"+skuNo+"】的sku的无税价和税价只能填一个");
}else if(taxFreePrice!=null&&taxFreePrice!=""){
if(taxFreePrice.matches("^[0-9]+(.[0-9]+)?$")){
vo.setTaxFreePrice(new BigDecimal(taxFreePrice));
}else {
return R.error("编号为:【"+skuNo+"】的sku的价钱"+"【"+taxFreePrice+"】不是数字格式");
}
}else if(freePrice!=null&&freePrice!=""){
if(freePrice.matches("^[0-9]+(.[0-9]+)?$")){
vo.setFreePrice(new BigDecimal(freePrice));
}else {
return R.error("编号为:【"+skuNo+"】的sku的价钱"+"【"+freePrice+"】不是数字格式");
}
}
if(taxRate!=null&&taxRate!=""){
if(taxRate.matches("^[0-9]+(.[0-9]+)?$")){
vo.setTaxRate(new BigDecimal(taxRate));
}else {
return R.error("编号为:【"+skuNo+"】的sku的价钱"+"【"+freePrice+"】不是数字格式");
}
}else {
return R.error("编号为:【"+skuNo+"】的税率不能为空");
}
if(skuNoList.contains(skuNo)){
return R.error("编号为:【"+skuNo+"】的sku重复导入");
}
if(salePrice==null||salePrice.equals("")){
return R.error("编号为:【"+skuNo+"】的销售价为空");
}else if(salePrice.matches("^[0-9]+(.[0-9]+)?$")){
vo.setSalePrice(new BigDecimal(salePrice));
}else {
return R.error("编号为:【"+skuNo+"】的sku的价钱"+"【"+salePrice+"】不是数字格式");
}
goodsExcleInpotVoList.add(vo);
}
if(goodsExcleInpotVoList.size()>0){
SupplierQuotationsDO sqo=new SupplierQuotationsDO();
sqo.setDr("0");
sqo.setCreateBy(ShiroUtils.getUser().getUsername());
sqo.setCreateNo(ShiroUtils.getUser().getUserNo());
sqo.setCreateTime(new Date());
sqo.setUpdateBy(ShiroUtils.getUser().getUsername());
sqo.setUpdateNo(ShiroUtils.getUser().getUserNo());
sqo.setUpdateTime(sqo.getUpdateTime());
Map<String,Object> map=new HashMap<>();
map.put("offset",0);
map.put("limit",1);
map.put("deptNo",goodsExcleInpotVoList.get(0).getDeptNo());
map.put("supplierNo",goodsExcleInpotVoList.get(0).getSupplierNo());
List<SupplierQuotationsDO> sss=supplierQuotationsService.list(map);
String tempOfferNo="";
String temp="";
if(sss!=null&&sss.size()>0){ //机构存在
tempOfferNo=sss.get(0).getOfferNo();
String vnum=sss.get(0).getVersionNumber();
temp=vnum.substring(3,vnum.length());
temp="v1."+(new Integer(temp)+1)+"";
}else{ //机构不存在
map.clear();
map.put("offset",0);
map.put("limit",1);
List<SupplierQuotationsDO> sid=supplierQuotationsService.list(map);
if(sid!=null&&sid.size()>0){
tempOfferNo="BJD"+SerialNumber.serial(sid.get(0).getOfferNo(),6);//BJD
temp="v1.0";
}else{
tempOfferNo="BJD000001";//BJD
temp="v1.0";
}
}
for(SupplierQuotationsExcleInpotVo so:goodsExcleInpotVoList){
so.setVersionNumber(temp);
so.setOfferNo(tempOfferNo);
sqo.setOfferDate(so.getOfferDate());
sqo.setOfferNo(so.getOfferNo());
sqo.setSupplierNo(so.getSupplierNo());
sqo.setSupplierName(so.getSupplierName());
sqo.setDeptName(so.getDeptName());
sqo.setDeptNo(so.getDeptNo());
sqo.setVersionNumber(so.getVersionNumber());
}
int offerId =supplierQuotationsService.saveVo(sqo);
for(SupplierQuotationsExcleInpotVo so:goodsExcleInpotVoList){
SupplierQuotationsDetailedDO o=new SupplierQuotationsDetailedDO();
o.setDr("0");
o.setBrand(so.getBrand());
o.setBrandNo(so.getBrandNo());
o.setFreePrice(so.getFreePrice());
o.setGoodsName(so.getGoodsName());
o.setGoodsSpec(so.getGoodsSpec());
o.setOfferId(Long.valueOf(offerId+""));
o.setOfferNo(so.getOfferNo());
o.setSkuNo(so.getSkuNo());
o.setTaxFreePrice(so.getTaxFreePrice());
o.setTaxRate(so.getTaxRate());
o.setUnit(so.getUnit());
o.setVersionNumber(so.getVersionNumber());
o.setSalePrice(so.getSalePrice());
tempNum+=supplierQuotationsDetailedService.save(o);
}
}
} catch (IOException e) {
e.printStackTrace();
return R.error("出现异常,导入失败");
}
if(tempNum==length){
return R.ok("导入成功");
}
return R.error("导入失败");
}
导出方法
/**
* 删除
*/
@GetMapping("/downloadExcleById")
@ResponseBody
//@RequiresPermissions("base:supplierQuotations:batchRemove")
public void updateVo(HttpServletResponse response, Long id) throws IOException {
if(id!=null){
Map<String,Object> map=new HashMap<>();
map.put("offerId",id);
map.put("drs",123456);
List<SupplierQuotationsDetailedDO> slist=supplierQuotationsDetailedService.list(map);
String name = "供应商报价单导出"+new Date().getTime();
response.setContentType("octets/stream");
response.addHeader("Content-Disposition", "attachment;filename=" + new String(name.getBytes("gb2312"), "ISO8859-1") + ".xls");
String[] headers = {"sku编号","sku名称","品牌","单位","规格","税率","无税价","含税价","销售价"};
OutputStream out = response.getOutputStream();
// 声明一个工作簿
HSSFWorkbook workbook = new HSSFWorkbook();
// 生成一个表格
HSSFSheet sheet = workbook.createSheet(name);
// 设置表格默认列宽度为15个字符
sheet.setDefaultColumnWidth(20);
// 产生表格标题行
HSSFRow row00 = sheet.createRow(0);
HSSFCell c00 = row00.createCell(0);
c00.setCellValue(new HSSFRichTextString("供应商名称:"));
HSSFCell c01 = row00.createCell(1);
c01.setCellValue(new HSSFRichTextString(supplierQuotationsService.get(id).getSupplierName()));
//CellRangeAddress 对象的构造方法需要传入合并单元格的首行、最后一行、首列、最后一列。
CellRangeAddress cra0=new CellRangeAddress(0, 0, 1, 7);
//合并单元格所使用的方法:
sheet.addMergedRegion(cra0);
// 产生表格标题行
HSSFRow row1 = sheet.createRow(1);
int o = 0;
for(int i=0;i<headers.length;i++){
row1.createCell(o++).setCellValue(headers[i].toString());
}
for (int i = 0; i < slist.size(); i++) {
int k = 1;
SupplierQuotationsDetailedDO DesignerQuotationDetailsDO = slist.get(i);
row1 = sheet.createRow(i + 1+k);
int j = 0; // ==null?"": ==null?"0":
row1.createCell(j++).setCellValue(DesignerQuotationDetailsDO.getSkuNo()==null?"":DesignerQuotationDetailsDO.getSkuNo().toString());
row1.createCell(j++).setCellValue(DesignerQuotationDetailsDO.getGoodsName()==null?"":DesignerQuotationDetailsDO.getGoodsName().toString());
row1.createCell(j++).setCellValue(DesignerQuotationDetailsDO.getBrand()==null?"":DesignerQuotationDetailsDO.getBrand().toString());
row1.createCell(j++).setCellValue(DesignerQuotationDetailsDO.getUnit()==null?"":DesignerQuotationDetailsDO.getUnit().toString());
row1.createCell(j++).setCellValue(DesignerQuotationDetailsDO.getGoodsSpec()==null?"":DesignerQuotationDetailsDO.getGoodsSpec().toString());
row1.createCell(j++).setCellValue(DesignerQuotationDetailsDO.getTaxRate()==null?"0":DesignerQuotationDetailsDO.getTaxRate().setScale(2,BigDecimal.ROUND_HALF_UP).toString());
row1.createCell(j++).setCellValue(DesignerQuotationDetailsDO.getTaxFreePrice()==null?"0":DesignerQuotationDetailsDO.getTaxFreePrice().setScale(2,BigDecimal.ROUND_HALF_UP).toString());
row1.createCell(j++).setCellValue(DesignerQuotationDetailsDO.getFreePrice()==null?"0":DesignerQuotationDetailsDO.getFreePrice().setScale(2,BigDecimal.ROUND_HALF_UP).toString());
row1.createCell(j++).setCellValue(DesignerQuotationDetailsDO.getSalePrice()==null?"0":DesignerQuotationDetailsDO.getSalePrice().setScale(2,BigDecimal.ROUND_HALF_UP).toString());
}
try {
workbook.write(out);
} catch (IOException e) {
e.printStackTrace();
}finally {
out.close();
}
}
}