XSSFWorkbook:是操作Excel2007的版本,扩展名是.xlsx
对于不同版本的EXCEL文档要使用不同的工具类,如果使用错了,会提示如下错误信息。
org.apache.poi.openxml4j.exceptions.InvalidOperationException
org.apache.poi.poifs.filesystem.OfficeXmlFileException
package com.tonicare.service.mgmt.sales; import java.io.File; import java.io.FileInputStream; import java.text.DecimalFormat; import java.text.SimpleDateFormat; import java.util.Date; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import org.apache.commons.io.FileUtils; import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.time.DateFormatUtils; import org.apache.commons.lang.time.DateUtils; 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.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.apache.struts2.components.Else; import com.tonicare.action.mgmt.sales.vo.SalesTmallStoreOrderVo; import com.tonicare.data.bean.CsStoreDate; import com.tonicare.data.bean.LmProduct; import com.tonicare.data.dao.SalesTMallDao; import com.tonicare.framework.layer.MgmtService; import com.tonicare.framework.layer.TonicareException; import com.tonicare.framework.layer.AjaxResultVo.StatusCode; import com.tonicare.util.BeanFactory; import com.tonicare.util.Config; import com.tonicare.util.Const; import com.tonicare.util.LogHelper; public class SalesTmallStoreOrderService extends MgmtService { @Override public Object invoke(Object inData) throws TonicareException { // TODO Auto-generated method stub SalesTmallStoreOrderVo vo=(SalesTmallStoreOrderVo) inData; if (Const.OPERATE_UPLOAD.equals(vo.getOpType())) { if (Config.DEBUG) { LogHelper.info("ExcelFileName=" + vo.getExcelFileName() + "\tExcelContentType=" + vo.getExcelContentType() + "\tExcel.AbsolutePath=" + vo.getExcel().getAbsolutePath()); vo.getAjaxResult().init(StatusCode.error); vo.getAjaxResult().setMessage("文件 " + vo.getExcelFileName() + "导入失败!"); } if (vo.getExcel()!=null) { Date now = new Date(); String fileName = DateFormatUtils.format(now, Const.TIME_FORMAT_NUMBER); int records= this.readExcel(vo.getExcel(), fileName,vo); vo.getAjaxResult().init(StatusCode.ok); vo.getAjaxResult().setMessage("文件 " + vo.getExcelFileName() + "(" + records + "条订单) 导入成功!"); } } return null; } public int readExcel(File aExcel, String aFile,SalesTmallStoreOrderVo vo) throws TonicareException{ int number=0; FileInputStream ins=null; try { Map<Long,LmProduct> maps=this.getProductsBymap(); SalesTMallDao dao=(SalesTMallDao) BeanFactory.getDao(Const.DAO_SALES_SALESTMALLDAO); ins=new FileInputStream(aExcel); XSSFWorkbook xb=new XSSFWorkbook(ins);//通过得到的文件流 创建一个HSSFWorkbook对象 XSSFSheet sheet=xb.getSheetAt(0); int rows=sheet.getPhysicalNumberOfRows(); XSSFRow row=null; //遍历 for(int i=1;i<=rows;i++){ row=sheet.getRow(i); if (row == null) { continue; } String sDate=vo.getStoredate().toString(); String aId=String.valueOf(this.getCell(row.getCell(3))); List<CsStoreDate> store=dao.getCsStoreDateByDateAndID(sDate,aId, null, null); CsStoreDate storebean=null; if(store==null || store.size()<=0){ storebean=new CsStoreDate(); }else{ storebean=store.get(0); storebean.setId(store.get(0).getId()); } storebean.setStoreDate(DateUtils.parseDate(vo.getStoredate(), Const.DEFAULT_DATE_FORMAT_ARRAY));//选择的时间 storebean.setStoreCode(vo.getShopid());//商超编码 storebean.setStoreName(String.valueOf(this.getCell(row.getCell(1))));//商超名称 if(this.getCell(row.getCell(2))==null || this.getCell(row.getCell(2)).equals("")){ storebean.setWarehouse(null);//仓库 }else{ storebean.setWarehouse(String.valueOf(this.getCell(row.getCell(2))));//仓库 } storebean.setProductId(String.valueOf(this.getCell(row.getCell(3))));//商品编码 storebean.setSkuId(null);//sku编码String.valueOf(this.getCell(row.getCell(4))) storebean.setProductName(String.valueOf(this.getCell(row.getCell(5))));//商品名称 if(this.getCell(row.getCell(7))==null || this.getCell(row.getCell(7)).equals("")){ storebean.setSupplierCode(null);//供应商id }else{ storebean.setSupplierCode(Integer.valueOf(String.valueOf(this.getCell(row.getCell(7)))));//供应商id } storebean.setSupplierName(String.valueOf(this.getCell(row.getCell(8))));//供应商名称 storebean.setMca1(String.valueOf(this.getCell(row.getCell(11))));//mcas一级类目 storebean.setMca2(String.valueOf(this.getCell(row.getCell(12))));//mcas二级类目 storebean.setMca3(String.valueOf(this.getCell(row.getCell(13))));//mcas三级类目 storebean.setMcaLast(String.valueOf(this.getCell(row.getCell(14))));//mcas末级类目 storebean.setWaiter(String.valueOf(this.getCell(row.getCell(16))));//招商小二 责任人 if(this.getCell(row.getCell(20))==null || this.getCell(row.getCell(20)).equals("")){ storebean.setStore(0);//库存数量 物流宝可销售库存数 }else{ storebean.setStore(Integer.parseInt(String.valueOf(this.getCell(row.getCell(20)))));//库存数量 物流宝可销售库存数 } if(this.getCell(row.getCell(21))==null || this.getCell(row.getCell(21)).equals("")){ storebean.setLockup(0);//库存数量 物流宝可销售库存数 }else{ storebean.setLockup(Integer.parseInt(String.valueOf(this.getCell(row.getCell(21)))));//锁定库存 物流宝锁定库数 } storebean.setGoodId(null);//商品条码 storebean.setSkuName(null);//规格名称 规格的值每次都是空的 直接做空处理 storebean.setStoreStatus(null);//库存状态 storebean.setOccupy(null);//占用数量 storebean.setCatId(null);//淘宝类目id storebean.setCatName(null);//淘宝类目名称 storebean.setWarehouse(null); storebean.setCreateTime(new Date());//更新时间 LmProduct pros=this.dealProduct(storebean,maps); if(pros!=null){ storebean.setDeleted(0); }else{ storebean.setDeleted(1);//删除标志 } dao.saveOrUpdate(storebean);//添加cs_store_date number++; } this.saveProductByMap(maps);//订单中有新品存在 就保存 this.saveExcel(aExcel, aFile);//备份excel文件 } catch (Exception e) { // TODO: handle exception number = 0; e.printStackTrace(); throw new TonicareException(); } return number; } //lmproduct产品表里面有的产品 库存表里面在标记为正常否则为删除商品 private LmProduct dealProduct(CsStoreDate aOrder, Map<Long,LmProduct> aMap) { LmProduct result = null; if (aOrder!=null) { Long productId = Long.valueOf(aOrder.getProductId().toString()); result = aMap.get(productId); if (result==null) { result = new LmProduct(); result.setId(Long.valueOf(aOrder.getProductId().toString())); result.setUpdateTime(new Date()); } result.setName(aOrder.getProductName()); result.setCode(aOrder.getGoodId()); aMap.put(productId, result); } return result; } public Object getCell(XSSFCell cell){ Object value=null; DecimalFormat df=new DecimalFormat("0");// 格式化 number String 字符 SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");// 格式化日期字符串 DecimalFormat nf=new DecimalFormat(); switch(cell.getCellType()){ case XSSFCell.CELL_TYPE_STRING: value=cell.getStringCellValue(); break; case XSSFCell.CELL_TYPE_NUMERIC: 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())); } break; case XSSFCell.CELL_TYPE_BOOLEAN: value=cell.getBooleanCellValue(); break; case XSSFCell.CELL_TYPE_BLANK: value=""; break; default: value=cell.toString(); break; } return value; } //将导入的库存的信息里面的新产品添加进产品信息里面 如果是已经存在的产品则更新产品名称和产品条码 private void saveProductByMap(Map<Long,LmProduct> aMap) { if (aMap!=null) { SalesTMallDao dao = (SalesTMallDao) BeanFactory.getDao(Const.DAO_SALES_SALESTMALLDAO); try { Iterator it = aMap.entrySet().iterator(); while (it.hasNext()) { Map.Entry<Long,LmProduct> entry = (Map.Entry<Long,LmProduct>) it.next(); long key = entry.getKey(); LmProduct val = entry.getValue(); LmProduct bean = dao.getProductById(key); if (bean==null) { bean = new LmProduct(); bean.setId(key);//商品id bean.setPlatform(2);//2 代表的是天猫平台 bean.setDeleted(0);//0 代表在售商品 bean.setUpdateTime(new Date()); } bean.setName(val.getName());//商品名称 dao.saveOrUpdate(bean); } } catch(Exception ex) { ex.printStackTrace(); } } } //得到天猫所有的产品 private Map<Long,LmProduct> getProductsBymap(){ Map<Long, LmProduct> map=new HashMap<Long, LmProduct>(); SalesTMallDao dao=(SalesTMallDao) BeanFactory.getDao(Const.DAO_SALES_SALESTMALLDAO); try { List<LmProduct> list=dao.getTmallProduct(); for(LmProduct row:list){ map.put(row.getId(),row); } } catch (Exception e) { // TODO: handle exception e.printStackTrace(); } return map; } //保存excel文件 private boolean saveExcel(File aSrc, String aFileName) { boolean result = false; String path = Config.UPLOAD_PATH + File.separator + "tmall" + File.separator + aFileName + ".xls"; try { File dst = new File(path); FileUtils.moveFile(aSrc, dst); result = true; }catch (Exception e) { result = false; e.printStackTrace(); } return result; } }