java中Excel处理工具类

/**
该工具类会返回处理结果和封装之后的数据,获取数据直接从

**/

import java.io.IOException;
import java.io.InputStream;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.poi.hssf.usermodel.HSSFCell;
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 org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.suixingpay.sms.admin.controller.profitTradeSum.ExcelProfitRead;
import com.suixingpay.sms.util.excel.ExcelCommon;

public class ExcelUtil {
   private static Logger LOGGER = LoggerFactory.getLogger(ExcelProfitRead.class);
   public static Map<String, Object> readExcel(String fileName,InputStream inputStream) throws Exception {
      Map<String, Object> excelMap = null;
      if (fileName == null || ExcelCommon.EMPTY.equals(fileName)) {
         excelMap = new HashMap<String,Object>();
         excelMap.put("readStatus", "error");
         excelMap.put("errorMsg", "无法读取Excel文件内容");
         return excelMap;
      } else {
         String postfix = getPostfix(fileName);
         if (!ExcelCommon.EMPTY.equals(postfix) && (ExcelCommon.OFFICE_EXCEL_2003_POSTFIX.equals(postfix.toLowerCase()) 
               || ExcelCommon.OFFICE_EXCEL_2010_POSTFIX.equals(postfix.toLowerCase()))) {
            if (ExcelCommon.OFFICE_EXCEL_2003_POSTFIX.equals(postfix.toLowerCase())) {
               excelMap = readXls(inputStream);
            } else if (ExcelCommon.OFFICE_EXCEL_2010_POSTFIX
                  .equals(postfix.toLowerCase())) {
               excelMap = readXlsx(inputStream);
            }
         } else {
            //Annotation      
            LOGGER.error(fileName + ExcelCommon.NOT_EXCEL_FILE);
            excelMap = new HashMap<String,Object>();
            excelMap.put("readStatus", "error");
            excelMap.put("errorMsg", "请选择Excel文件上传");
            return excelMap;
         }
      }
      return excelMap;
   }
   
   public static String getPostfix(String fileName) throws Exception{
      if (fileName == null || ExcelCommon.EMPTY.equals(fileName.trim())) {
         return ExcelCommon.EMPTY;
      }
      if (fileName.contains(ExcelCommon.POINT)) {
         return fileName.substring(fileName.lastIndexOf(ExcelCommon.POINT) + 1,
               fileName.length());
      }
      return ExcelCommon.EMPTY;
   }
   
   public static Map<String, Object> readXls(InputStream inputStream) throws Exception{
      LOGGER.info("Read the Excel 2003-2007");
      List<List<Object>> dataList = new ArrayList<List<Object>>();
      Map<String, Object> excelMap = new HashMap<String, Object>();
      HSSFWorkbook wb=null;
      try {
         wb = new HSSFWorkbook(inputStream);
      } catch (IOException e) {
         excelMap.put("readStatus", "error");
         excelMap.put("errorMsg", "无法读取Excel文件内容");
         e.printStackTrace();
         return excelMap;
      }
      HSSFSheet sheet = wb.getSheetAt(0);
      HSSFRow row = null;
      HSSFCell cell = null;
      Object val = null;
      DecimalFormat df = new DecimalFormat("#,###,##0.00");// 格式化数字
      SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// 格式化日期字符串
      try {
         for (int i = sheet.getFirstRowNum(); i < sheet
               .getPhysicalNumberOfRows(); i++) {
            row = sheet.getRow(i);
            if (row == null) {
               continue;
            }
            List<Object> objList = new ArrayList<Object>();
            for (int j = row.getFirstCellNum(); j < row.getLastCellNum(); j++) {
               cell = row.getCell(j);
               if (cell == null) {
                  val = null;
                  objList.add(val);
                  continue;
               }
               switch (cell.getCellType()) {
               case HSSFCell.CELL_TYPE_STRING:
                  val = cell.getStringCellValue();
                  break;
               case HSSFCell.CELL_TYPE_NUMERIC:
                  if ("@".equals(cell.getCellStyle().getDataFormatString())) {
                     val = df.format(cell.getNumericCellValue());
                  } else if ("General".equals(cell.getCellStyle().getDataFormatString())) {
                     val = df.format(cell.getNumericCellValue());
                  } else {
                     //val = sdf.format(HSSFDateUtil.getJavaDate(cell.getNumericCellValue()));
                     val = df.format(cell.getNumericCellValue());
                  }
                  break;
               case HSSFCell.CELL_TYPE_BOOLEAN:
                  val = cell.getBooleanCellValue();
                  break;
               case HSSFCell.CELL_TYPE_BLANK:
                  val = "";
                  break;
               default:
                  val = cell.toString();
                  break;
               }
               objList.add(val);
            }
            dataList.add(objList);
         }
         excelMap.put("readStatus", "pass");
         excelMap.put("dataList", dataList);
      } catch (Exception e) {
         e.printStackTrace();
         excelMap.put("readStatus", "error");
         excelMap.put("errorMsg", "导入出错,请联系管理员");
      }
      return excelMap;
   }
   
   public static Map<String, Object> readXlsx(InputStream inputStream) throws Exception{
      LOGGER.info("Read the Excel 2010");
      Map<String, Object> excelMap = new HashMap<String, Object>();
      List<List<Object>> dataList = new ArrayList<List<Object>>();
      XSSFWorkbook xssfWorkbook = null;
      try {
         xssfWorkbook = new XSSFWorkbook(inputStream);
      }catch (IOException e) {
         excelMap.put("readStatus", "error");
         excelMap.put("errorMsg", "无法读取Excel文件内容");
         e.printStackTrace();
         return excelMap;
      }
      //读取台卡类营销政策sheet页
      XSSFSheet sheet = xssfWorkbook.getSheetAt(0);
      XSSFRow row = null;
      XSSFCell cell = null;
      Object val = null;
      DecimalFormat df = new DecimalFormat("#0.00");// 格式化数字
      SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// 格式化日期字符串
      try {
         for (int i = sheet.getFirstRowNum(); i < sheet
               .getPhysicalNumberOfRows(); i++) {
            row = sheet.getRow(i);
            if (row == null) {
               continue;
            }
            List<Object> objList = new ArrayList<Object>();
            for (int j = row.getFirstCellNum(); j < row.getLastCellNum(); j++) {
               cell = row.getCell(j);
               if (cell == null) {
                  val = null;
                  objList.add(val);
                  continue;
               }
               switch (cell.getCellType()) {
               case XSSFCell.CELL_TYPE_STRING:
                  val = cell.getStringCellValue();
                  break;
               case XSSFCell.CELL_TYPE_NUMERIC:
                  if ("@".equals(cell.getCellStyle().getDataFormatString())) {
                     val = df.format(cell.getNumericCellValue());
                  } else if ("General".equals(cell.getCellStyle().getDataFormatString())) {
                     val = df.format(cell.getNumericCellValue());
                  } else {
                     val = df.format(cell.getNumericCellValue());
                  }
                  break;
               case XSSFCell.CELL_TYPE_BOOLEAN:
                  val = cell.getBooleanCellValue();
                  break;
               case XSSFCell.CELL_TYPE_BLANK:
                  val = "";
                  break;
               default:
                  val = cell.toString();
                  break;
               }
               objList.add(val);
            }
            dataList.add(objList);
         }
         excelMap.put("readStatus", "pass");
         excelMap.put("dataList", dataList);
      } catch (Exception e) {
         e.printStackTrace();
         excelMap.put("readStatus", "error");
         excelMap.put("errorMsg", "导入出错,请联系管理员");
      }
      return excelMap;
   }
}

使用示例

//解析excel
Map<String, Object> resultMap = null;
resultMap = readExcel(excelFile.getOriginalFilename(),excelFile.getInputStream())
List<List<Object>> listNumbers = new ArrayList<List<Object>>();//导入数据的list集合
listNumbers = (List<List<Object>>) resultMap.get("dataList");//导入数据的条数符合要求
if (listNumbers.size() == 1) {//导入的数据为空
   model.addAttribute("col", "导入的Excel数据为空!");
   changeInfoRecord.setPreviousInfo("导入的Excel数据为空!");
   changeInfoRecordService.saveChangeInfoRecord(changeInfoRecord);
   return "newprofit/newProfitImportResult";
}
List<Map<String,String>> resultList=new ArrayList<Map<String,String>>();//用于存放批量导入时的错误信息
outDetailImport(listNumbers, resultList);
private void outDetailImport(List<List<Object>> listNumbers, List<Map<String, String>> resultList) {
   //代理商编号,代理商名称,调整数据(补发),调整说明(补发),调整数据(补扣无需开票),调整说明(补扣无需开票),调整数据(补扣需开票)
   //,调整说明(补扣需开票),扣除机具款项,台卡类营销政策分润,机具类营销政策分润,维护费,损失数据,嗨go分润
   for (int j = 1; j < listNumbers.size(); j++) {//遍历所传的数据集合
      List<Object> list = listNumbers.get(j);
      logger.info("第"+j+"条数据:"+list.toString());
      Map<String, String> map = new HashMap<String, String>();
      if (null == list.get(0) || "".equals(list.get(0))) {//机构编号为空
         map.put("error", "第" + j + "条数据有误,检测到代理商编号为空,请修改后再操作导入!");
         resultList.add(map);
         continue;
      } else {//机构编号不为空
         if (list.get(0).toString().length() != 10) {//机构编号不为10位数字
            map.put("error", "第" + j + "条数据有误,检测到代理商编号"+list.get(0)+"输入有误,请修改后再操作导入!");
            resultList.add(map);
            continue;
         }
         if(!orgService.isAllStsTopOrg((String)list.get(0))) {
            map.put("error", "第" + j + "条数据有误,检测到代理商编号"+list.get(0)+"为非一代代理商,请修改后再操作导入!");
            resultList.add(map);
            continue;
         }
         if("2".equals(orgService.getExpandMercTypeByOrgNo((String)list.get(0)))) {
            map.put("error", "第" + j + "条数据有误,检测到代理商编号"+list.get(0)+"为非优质代理商,请修改后再操作导入!");
            resultList.add(map);
            continue;
         }

      }
      //调整数据(补发)校验
      if(null!=list.get(2)&&!"".equals(list.get(2).toString())){
         boolean flag = list.get(2).toString().matches("^[+]{0,1}(\\d+)$|^[+]{0,1}(\\d+\\.\\d+)$");
         if(!flag) {
            map.put("error", "第" + j + "条数据有误,调整数据(补发)为正数,请修改后再操作导入!");
            resultList.add(map);
            continue;
         }
      }
      //调整数据(补扣无需开票)校验
      if(null!=list.get(4)&&!"".equals(list.get(4).toString())){
         boolean flag = list.get(4).toString().matches("^[+]{0,1}(\\d+)$|^[+]{0,1}(\\d+\\.\\d+)$");
         if(!flag) {
            map.put("error", "第" + j + "条数据有误,调整数据(补扣无需开票)为正数,请修改后再操作导入!");
            resultList.add(map);
            continue;
         }
      }
      //调整数据(补扣需开票)校验
      if(null!=list.get(6)&&!"".equals(list.get(6).toString())){
         boolean flag = list.get(6).toString().matches("^[+]{0,1}(\\d+)$|^[+]{0,1}(\\d+\\.\\d+)$");
         if(!flag) {
            map.put("error", "第" + j + "条数据有误,调整数据(补扣需开票)为正数,请修改后再操作导入!");
            resultList.add(map);
            continue;
         }
      }
      //扣除机具款校验
      if(null!=list.get(8)&&!"".equals(list.get(8).toString())){
         boolean flag = list.get(8).toString().matches("^[+]{0,1}(\\d+)$|^[+]{0,1}(\\d+\\.\\d+)$");
         if(!flag) {
            map.put("error", "第" + j + "条数据有误,扣除机具款项为正数,请修改后再操作导入!");
            resultList.add(map);
            continue;
         }
      }
      //台卡类营销政策分润校验
      if(null!=list.get(9)&&!"".equals(list.get(9).toString())){
         boolean flag = list.get(9).toString().matches("^[+]{0,1}(\\d+)$|^[+]{0,1}(\\d+\\.\\d+)$");
         if(!flag) {
            map.put("error", "第" + j + "条数据有误,台卡类营销政策分润为正数,请修改后再操作导入!");
            resultList.add(map);
            continue;
         }
      }
      //机具类营销政策分润校验
      if(null!=list.get(10)&&!"".equals(list.get(10).toString())){
         boolean flag = list.get(10).toString().matches("^[+]{0,1}(\\d+)$|^[+]{0,1}(\\d+\\.\\d+)$");
         if(!flag) {
            map.put("error", "第" + j + "条数据有误,机具类营销政策分润为正数,请修改后再操作导入!");
            resultList.add(map);
            continue;
         }
      }
      //维护费分润校验
      if(null!=list.get(11)&&!"".equals(list.get(11).toString())){
         boolean flag = list.get(11).toString().matches("^[+]{0,1}(\\d+)$|^[+]{0,1}(\\d+\\.\\d+)$");
         if(!flag) {
            map.put("error", "第" + j + "条数据有误,维护费为正数,请修改后再操作导入!");
            resultList.add(map);
            continue;
         }
      }
      //损失数据校验
      if(null!=list.get(12)&&!"".equals(list.get(12).toString())){
         boolean flag = list.get(12).toString().matches("^[+]{0,1}(\\d+)$|^[+]{0,1}(\\d+\\.\\d+)$");
         if(!flag) {
            map.put("error", "第" + j + "条数据有误,损失数据为正数,请修改后再操作导入!");
            resultList.add(map);
            continue;
         }
      }
      //嗨go分润校验
      if(null!=list.get(13)&&!"".equals(list.get(13).toString())){
         boolean flag = list.get(13).toString().matches("^[+]{0,1}(\\d+)$|^[+]{0,1}(\\d+\\.\\d+)$");
         if(!flag) {
            map.put("error", "第" + j + "条数据有误,机具类营销政策分润为正数,请修改后再操作导入!");
            resultList.add(map);
            continue;
         }
      }
      continue;
   }
}

猜你喜欢

转载自blog.csdn.net/m0_37708405/article/details/82056903