excelUtil
发布日期:2021-05-07 00:04:22 浏览次数:20 分类:精选文章

本文共 30249 字,大约阅读时间需要 100 分钟。

package com.taobao.service;import java.io.ByteArrayOutputStream;import java.io.File;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.text.DecimalFormat;import java.text.SimpleDateFormat;import java.util.ArrayList;import java.util.Calendar;import java.util.Comparator;import java.util.Date;import java.util.HashMap;import java.util.Iterator;import java.util.List;import java.util.Map;import org.apache.log4j.Logger;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.IndexedColors;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;import org.springframework.web.multipart.MultipartFile;import com.taobao.bean.ProductQuery;import com.taobao.bean.SupplyProduct;import com.taobao.bean.User;import com.taobao.dao.ExpressDAO;import com.taobao.dao.OrderDAO;import com.taobao.dao.ProductDAO;import com.taobao.dto.Product;import com.taobao.exception.UploadDownloadException;import com.taobao.listener.CloudPrintManager;import cn.fita.bean.Page;public class ExcelService {	private static Logger log = Logger.getLogger(ExcelService.class);	private static final String XLS = "xls";	private static final String XLSX = "xlsx";	private ProductService pservice = new ProductService();	private ConstantService cservice = new ConstantService();	private ExpressDAO edao = new ExpressDAO();	private ProductDAO pdao = new ProductDAO();	private OrderDAO dao = new OrderDAO();	/**	 * 根据文件后缀名类型获取对应的工作簿对象	 * 	 * @param inputStream	 *            读取文件的输入流	 * @param fileType	 *            文件后缀名类型(xls或xlsx)	 * @return 包含文件数据的工作簿对象	 * @throws IOException	 */	public static Workbook getWorkbook(InputStream inputStream, String fileType) throws IOException {		Workbook workbook = null;		if (fileType.equalsIgnoreCase(XLS)) {			workbook = new HSSFWorkbook(inputStream);		} else if (fileType.equalsIgnoreCase(XLSX)) {			workbook = new XSSFWorkbook(inputStream);		}		return workbook;	}	/**	 * 读取Excel文件内容	 * 	 * @param fileName	 *            要读取的Excel文件所在路径	 * @return 读取结果列表,读取失败时返回null	 */	public static List
readExcel(String fileName) { Workbook workbook = null; FileInputStream inputStream = null; // 获取Excel后缀名 String fileType = fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length()); // 获取Excel文件 File excelFile = new File(fileName); if (!excelFile.exists()) { log.info("指定的Excel文件不存在!"); return null; } return readExcel(inputStream, fileType); } public static List
readExcel(InputStream inputStream,String fileType) { Workbook workbook = null; try { workbook = getWorkbook(inputStream, fileType); // 读取excel中的数据 List
resultDataList = parseExcel(workbook); return resultDataList; } catch (Exception e) { log.info("解析Excel失败! 错误信息:" + e.getMessage()); return null; } finally { try { if (null != inputStream) { inputStream.close(); } } catch (Exception e) { log.info("关闭数据流出错!错误信息:" + e.getMessage()); return null; } } } /** * 解析Excel数据 * * @param workbook * Excel工作簿对象 * @return 解析结果 */ private static List
parseExcel(Workbook workbook) { List
resultDataList = new ArrayList<>(); // 解析sheet for (int sheetNum = 0; sheetNum < workbook.getNumberOfSheets(); sheetNum++) { Sheet sheet = workbook.getSheetAt(sheetNum); // 校验sheet是否合法 if (sheet == null) { continue; } // 获取第一行数据 int firstRowNum = sheet.getFirstRowNum(); Row firstRow = sheet.getRow(firstRowNum); if (null == firstRow) { log.info("解析Excel失败,在第一行没有读取到任何数据!"); } // 解析每一行的数据,构造数据对象 int rowStart = firstRowNum + 1; int rowEnd = sheet.getPhysicalNumberOfRows(); for (int rowNum = rowStart; rowNum < rowEnd; rowNum++) { Row row = sheet.getRow(rowNum); if (null == row) { continue; } Product resultData = convertRowToData(row); if (null == resultData) { log.info("第 " + row.getRowNum() + "行数据不合法,已忽略!"); continue; } resultDataList.add(resultData); } } return resultDataList; } /** * 将单元格内容转换为字符串 * * @param cell * @return */ private static String convertCellValueToString(Cell cell) { if (cell == null) { return null; } String returnValue = null; switch (cell.getCellType()) { case Cell.CELL_TYPE_NUMERIC: // 数字 Double doubleValue = cell.getNumericCellValue(); // 格式化科学计数法,取一位整数 DecimalFormat df = new DecimalFormat("0"); returnValue = df.format(doubleValue); break; case Cell.CELL_TYPE_STRING: // 字符串 returnValue = cell.getStringCellValue(); break; case Cell.CELL_TYPE_BOOLEAN: // 布尔 Boolean booleanValue = cell.getBooleanCellValue(); returnValue = booleanValue.toString(); break; case Cell.CELL_TYPE_BLANK: // 空值 break; case Cell.CELL_TYPE_FORMULA: // 公式 returnValue = cell.getCellFormula(); break; case Cell.CELL_TYPE_ERROR: // 故障 break; default: break; } return returnValue; } /** * 提取每一行中需要的数据,构造成为一个结果数据对象 * * 当该行中有单元格的数据为空或不合法时,忽略该行的数据 * * @param row * 行数据 * @return 解析后的行数据对象,行数据错误时返回null */ private static Product convertRowToData(Row row) { Product product = new Product(); Cell cell; int cellNum = 0; // 获取编码 cell = row.getCell(cellNum++); String pid = convertCellValueToString(cell); if(pid==null){ return null; } product.setPid(pid); // 获取名称 cell = row.getCell(cellNum++); String name = convertCellValueToString(cell); product.setName(name); // 获取书架号 cell = row.getCell(cellNum++); String bookshelf = convertCellValueToString(cell); product.setBookshelf(bookshelf); // 获取库存 cell = row.getCell(cellNum++); String stock = convertCellValueToString(cell); if(stock==null){ return null; } product.setStock(Integer.parseInt(stock)); return product; } /** * 将数据转换成行 * * @param data * 源数据 * @param row * 行对象 * @return */ private static void convertDataToRow(Product product, Row row, CellStyle cellStyle) { int cellNum = 0; Cell cell; cell = row.createCell(cellNum++); cell.setCellStyle(cellStyle); cell.setCellValue(null == product.getPid() ? "" : product.getPid()); cell = row.createCell(cellNum++); cell.setCellStyle(cellStyle); cell.setCellValue(null == product.getName() ? "" : product.getName()); cell = row.createCell(cellNum++); cell.setCellStyle(cellStyle); cell.setCellValue(null == product.getBookshelf() ? "" : product.getBookshelf()); cell = row.createCell(cellNum++); cell.setCellStyle(cellStyle); cell.setCellValue(product.getStock()); } private static CellStyle buildCellStyle(Workbook workbook) { CellStyle style = workbook.createCellStyle(); // 对齐方式设置 style.setAlignment(CellStyle.ALIGN_CENTER); style.setVerticalAlignment(CellStyle.VERTICAL_CENTER); // 边框颜色和宽度设置 style.setBorderBottom(CellStyle.BORDER_THIN); style.setBottomBorderColor(IndexedColors.BLACK.getIndex()); // 下边框 style.setBorderLeft(CellStyle.BORDER_THIN); style.setLeftBorderColor(IndexedColors.BLACK.getIndex()); // 左边框 style.setBorderRight(CellStyle.BORDER_THIN); style.setRightBorderColor(IndexedColors.BLACK.getIndex()); // 右边框 style.setBorderTop(CellStyle.BORDER_THIN); style.setTopBorderColor(IndexedColors.BLACK.getIndex()); // 上边框 return style; } public ByteArrayOutputStream getDownloadData( List
> sourceList) {// Page page = new Page();// page.setPerPage(99999);// List
> nailList = pservice.queryProduct(0, 2, "", "", page, 0, "");// List
> stationeryList = pservice.queryProduct(0, 3, "", "", page, 0, "");// List
> bookList = pservice.queryProduct(0, 4, "", "", page, 0, ""); List
list = new ArrayList
(); convertDataToProductList(sourceList, list);// convertDataToProductList(nailList, list);// convertDataToProductList(stationeryList, list);// convertDataToProductList(bookList, list);// ComparatorChain chain = new ComparatorChain();// chain.addComparator(getBookShelfComparator());// chain.addComparator(getPidComparator());// Collections.sort(list, chain); File file = new File(cservice.getConstant("templatepath")); ByteArrayOutputStream baos = new ByteArrayOutputStream(); try { Workbook workbook = ExcelService.getWorkbook(new FileInputStream(file), ExcelService.XLSX); Sheet sheet0 = workbook.getSheetAt(0); CellStyle cellStyle = ExcelService.buildCellStyle(workbook); int rowNum = 1; for (Iterator
it = list.iterator(); it.hasNext();) { Product data = it.next(); if (data == null) { continue; } // 输出行数据 Row row = sheet0.createRow(rowNum++); convertDataToRow(data, row, cellStyle); } SimpleDateFormat sdf = new SimpleDateFormat("yyyy_MM_dd"); SimpleDateFormat sdf2 = new SimpleDateFormat("HH_mm_ss"); File fileDir = new File(cservice.getConstant("downloadpath") + sdf.format(new Date()) ); if (!fileDir.exists()){ fileDir.mkdirs(); } String outputPath = fileDir.getCanonicalPath()+File.separator +sdf2.format(new Date())+ ".xlsx"; FileOutputStream fo = new FileOutputStream(new File(outputPath)); workbook.write(fo); fo.close(); fo.flush(); FileInputStream fi = new FileInputStream(new File(outputPath)); int data = -1; while ((data = fi.read()) != -1) { baos.write(data); } fi.close(); baos.close(); } catch (Exception e) { e.printStackTrace(); } return baos; } private void convertDataToProductList(List
> sourceList, List
targetList) { for (int i = 0; i < sourceList.size(); i++) { String pid = String.valueOf(sourceList.get(i).get("pid")); String name = String.valueOf(sourceList.get(i).get("name")); String bookshelf = String.valueOf(sourceList.get(i).get("bookshelf")); int stock = Integer.parseInt(String.valueOf(sourceList.get(i).get("stock"))); Product product = new Product(); product.setPid(pid); product.setName(name); product.setBookshelf(bookshelf); product.setStock(stock); targetList.add(product); } } public static Comparator
getBookShelfComparator() { return new Comparator
() { @Override public int compare(Product product1, Product product2) { return product2.getBookshelf().compareTo(product1.getBookshelf()); } }; } public static Comparator
getPidComparator() { return new Comparator
() { @Override public int compare(Product product1, Product product2) { return product1.getPid().compareTo(product2.getPid()); } }; } public void uploadExcel( User user,MultipartFile mFile,boolean needOffLock) throws Exception { if (mFile == null) { throw new Exception("请选择上传文件"); } if (mFile.isEmpty()) { throw new Exception("不允许上传空文件"); } SimpleDateFormat sdf = new SimpleDateFormat("yyyy_MM_dd"); String dateDir = sdf.format(new Date()); File fileDir = new File(cservice.getConstant("uploadpath") + dateDir); // 判定目录是否存在,不存在则创建 if (!fileDir.exists()){ fileDir.mkdirs(); } // 构建文件对象(fileDir为目录,mFile.getOriginalFilename()文件名) String fileName = mFile.getOriginalFilename(); File dest = new File(fileDir, fileName); mFile.transferTo(dest); //读取数据 InputStream inputStream = mFile.getInputStream(); String fileType = fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length()); List
list = readExcel(inputStream, fileType); Page page = new Page(); page.setPerPage(999999); ProductQuery productQuery = new ProductQuery(0, 0, "", "",0,"",""); List
> pList = pservice.queryProduct(productQuery, page); for (int i = 0; i < list.size(); i++) { Product product = list.get(i); if(needOffLock){ product.setReason("解除锁定"); product.setType("8"); }else{ product.setReason("批量修改"); product.setType("6"); } int stock = 0; for (int j = 0; j < pList.size(); j++) { String pid = String.valueOf(pList.get(j).get("pid")); if( pid.equals(product.getPid())){ stock = Integer.parseInt(String.valueOf(pList.get(j).get("stock"))); log.info("批量修改:"+ product.getPid() +" 数量:"+ product.getStock()+" 原库存:"+ stock +" 相差:"+ String.valueOf(stock-product.getStock()) ); pservice.updateProduct(product, user); } } if(needOffLock){ pservice.productLock(product.getPid(),"0"); pdao.addLockStockId(product); pservice.changeProductLockByPidAndTime("1",product.getPid(),product.getStock(),stock); } } } public ByteArrayOutputStream getPddExcel(String dateStr) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); try { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); Date date = sdf.parse(dateStr); Calendar cal = Calendar.getInstance(); cal.setTime(date); cal.add(Calendar.DATE,1); List
> list = edao.getPddSendData(dateStr,sdf.format(cal.getTime())); String outputPath = createPddExcel(list); FileInputStream fi = new FileInputStream(new File(outputPath)); int data = -1; while ((data = fi.read()) != -1) { baos.write(data); } fi.close(); baos.close(); } catch (Exception e) { e.printStackTrace(); } return baos; } /** * @see 创建Pdd excel 文件 用于批量发货功能 * @param list * @return */ public String createPddExcel(List
> list){ File file = new File(cservice.getConstant("pddexcelpath")+"temp.xlsx"); try { FileInputStream fi = new FileInputStream(file); Workbook workbook = ExcelService.getWorkbook(fi, ExcelService.XLSX); Sheet sheet0 = workbook.getSheetAt(0); CellStyle cellStyle = ExcelService.buildCellStyle(workbook); int rowNum = 2; for (int i = 0; i < list.size(); i++) { Row row = sheet0.createRow(rowNum++); int cellNum = 0; Cell cell; cell = row.createCell(cellNum++); cell.setCellStyle(cellStyle); String val = String.valueOf(list.get(i).get("oid")); cell.setCellValue(val); cell = row.createCell(cellNum++); cell.setCellStyle(cellStyle); val = String.valueOf(list.get(i).get("ecid")); if( "4".equals(val) ){ val = "韵达快递"; }else if( "3".equals(val) ){ val = "邮政EMS"; }else if( "6".equals(val) ){ val = "顺丰快递"; }else if( "8".equals(val) ){ val = "邮政快递包裹"; }else if( "1".equals(val) ){ val = "中通快递"; }else if( "5".equals(val) ){ val = "申通快递"; } cell.setCellValue(val); cell = row.createCell(cellNum++); cell.setCellStyle(cellStyle); val = String.valueOf(list.get(i).get("eid")); cell.setCellValue(val); } File fileDir = new File(cservice.getConstant("pddexcelpath")+"result_"+System.currentTimeMillis()+".xlsx"); String outputPath = fileDir.getCanonicalPath(); FileOutputStream fo = new FileOutputStream(new File(outputPath)); workbook.write(fo); fi.close(); fo.close(); fo.flush(); return outputPath; } catch (Exception e) { e.printStackTrace(); } return ""; } public static void createWoDaExcel(List
> list){ File file = new File("/Volumes/disksd/work/test/temp2.xlsx"); try { Workbook workbook = ExcelService.getWorkbook(new FileInputStream(file), ExcelService.XLSX); Sheet sheet0 = workbook.getSheetAt(0); List
listE = new ArrayList
(); CellStyle cellStyle = ExcelService.buildCellStyle(workbook); int rowNum = 1; for (int i = 0; i < list.size(); i++) { String val = String.valueOf(list.get(i).get("oid")); if( listE.contains( String.valueOf(list.get(i).get("eid"))) ){ System.out.println(val + "___" + String.valueOf(list.get(i).get("eid"))); continue; }else{ listE.add( String.valueOf(list.get(i).get("eid"))); } Row row = sheet0.createRow(rowNum++); int cellNum = 0; Cell cell; cell = row.createCell(cellNum++); cell.setCellStyle(cellStyle); cell.setCellValue(val); cell = row.createCell(cellNum++); cell.setCellStyle(cellStyle); if( String.valueOf(list.get(i).get("eid")) .startsWith("4") ){ val = "韵达快递"; }else{ val = "邮政快递包裹"; } cell.setCellValue(val); cell = row.createCell(cellNum++); cell.setCellStyle(cellStyle); val = String.valueOf(list.get(i).get("eid")); cell.setCellValue(val); } File fileDir = new File("/Volumes/disksd/work/test/result2.xlsx"); String outputPath = fileDir.getCanonicalPath(); FileOutputStream fo = new FileOutputStream(new File(outputPath)); workbook.write(fo); fo.close(); fo.flush(); } catch (Exception e) { e.printStackTrace(); } } private static void convertPressDataToRow(Map
map, Row row, CellStyle cellStyle) { int cellNum = 0; Cell cell; cell = row.createCell(cellNum++); cell.setCellStyle(cellStyle); cell.setCellValue(null == map.get("updateTime") ? "" : String.valueOf(map.get("updateTime"))); cell = row.createCell(cellNum++); cell.setCellStyle(cellStyle); cell.setCellValue(null == map.get("邮政") ? 0 : Integer.parseInt(String.valueOf(map.get("邮政")))); cell = row.createCell(cellNum++); cell.setCellStyle(cellStyle); cell.setCellValue(null == map.get("EMS") ? 0 : Integer.parseInt(String.valueOf(map.get("EMS")))); cell = row.createCell(cellNum++); cell.setCellStyle(cellStyle); cell.setCellValue(null == map.get("韵达") ? 0 : Integer.parseInt(String.valueOf(map.get("韵达")))); cell = row.createCell(cellNum++); cell.setCellStyle(cellStyle); cell.setCellValue(null == map.get("申通") ? 0 : Integer.parseInt(String.valueOf(map.get("申通")))); cell = row.createCell(cellNum++); cell.setCellStyle(cellStyle); cell.setCellValue(null == map.get("顺丰") ? 0 : Integer.parseInt(String.valueOf(map.get("顺丰")))); cell = row.createCell(cellNum++); cell.setCellStyle(cellStyle); cell.setCellValue(null == map.get("总单数") ? 0 : Integer.parseInt(String.valueOf(map.get("总单数")))); cell = row.createCell(cellNum++); cell.setCellStyle(cellStyle); cell.setCellValue(null == map.get("错单") ? 0 : Integer.parseInt(String.valueOf(map.get("错单")))); cell = row.createCell(cellNum++); cell.setCellStyle(cellStyle); cell.setCellValue(null == map.get("漏单") ? 0 : Integer.parseInt(String.valueOf(map.get("漏单")))); } public ByteArrayOutputStream getOutBordRecord(String startTime,String endTime) { File excelFile = new File(cservice.getConstant("tempexportpath")); List
> changeList = pdao.queryMissAndErrorForKPI(startTime,endTime,null,1); List
> perEcidList = dao.queryPerEcidNUm(startTime,endTime); List
> listAll=new ArrayList<>(); coverExpressData(listAll,perEcidList,changeList); Workbook workbook; ByteArrayOutputStream baos = new ByteArrayOutputStream(); try { if (!excelFile.exists()) { log.warn("模板Excel文件不存在!"); return null; } workbook = ExcelService.getWorkbook(new FileInputStream(excelFile), ExcelService.XLSX); Sheet sheet0 = workbook.getSheetAt(0); CellStyle cellStyle = ExcelService.buildCellStyle(workbook); int rowNum = 2; for (Iterator
> it = listAll.iterator(); it.hasNext();) { Map
map = it.next(); if (map == null) { continue; } // 输出行数据 Row row = sheet0.createRow(rowNum++); convertPressDataToRow(map, row, cellStyle); } workbook.write(baos); baos.flush(); baos.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return baos; } public void coverExpressData(List
> list,List
> perEcidList, List
> changeList){ for(int i=0;i
map = new HashMap<>(); String updateTime = String.valueOf(perEcidList.get(i).get("updatetime")); String[] ecnames = String.valueOf(perEcidList.get(i).get("ecname")).split(","); String[] counts = String.valueOf(perEcidList.get(i).get("count")).split(","); String sum = String.valueOf(perEcidList.get(i).get("sum")); map.put("updateTime", updateTime); map.put("总单数", sum); for(int t=0;t
> list = dao.queryReceiveRecord("","","","",null,tid,"","","",0); File excelFile = new File(cservice.getConstant("downreceivepath")); Workbook workbook; ByteArrayOutputStream baos = new ByteArrayOutputStream(); try { if (!excelFile.exists()) { log.warn("模板Excel文件不存在!"); return null; } workbook = ExcelService.getWorkbook(new FileInputStream(excelFile), ExcelService.XLSX); Sheet sheet0 = workbook.getSheetAt(0); CellStyle cellStyle = ExcelService.buildCellStyle(workbook); Iterator
> it = list.iterator(); int rowNum=2; int num=1; double priceAllSum=0.0; double discountAllPriceSum=0.0; int countNum=0; while (it.hasNext()) { Map
map = it.next(); if (map == null) { continue; } String pname=String.valueOf(map.get("pname")); String pid=String.valueOf(map.get("pid")); if(map.get("pname")!=null){ pname=pservice.convertPname(pid, pname); map.put("pname", pname); } discountAllPriceSum += Double.parseDouble(String.valueOf(map.get("realallprice"))); priceAllSum += Double.parseDouble(String.valueOf(map.get("allprice"))); countNum += Double.parseDouble(String.valueOf(map.get("receivernum"))); Row row = sheet0.createRow(rowNum++); convertReceiveRecordDataToRow(map, row, cellStyle,num++); } Row expressRow = sheet0.createRow(rowNum); countReceiveRecordExpressRow(num,expressRow,cellStyle); Row lastRow = sheet0.createRow(rowNum+1); countReceiveRecordDataToLastRow(priceAllSum,discountAllPriceSum,countNum,lastRow,cellStyle); workbook.write(baos); baos.flush(); baos.close(); } catch (IOException e) { e.printStackTrace(); } if(baos.size()>0){ dao.updataReceiveRecordByTid(tid); } return baos; } public void convertReceiveRecordDataToRow(Map
map, Row row, CellStyle cellStyle,int num) { int cellNum=0; Cell cell; cell = row.createCell(cellNum++); cell.setCellStyle(cellStyle); cell.setCellValue(String.valueOf(num)); cell = row.createCell(cellNum++); cell.setCellStyle(cellStyle); cell.setCellValue(null== map.get("pname") ? "": String.valueOf(map.get("pname"))); cell = row.createCell(cellNum++); cell.setCellStyle(cellStyle); cell.setCellValue(null==map.get("pid") ? "": String.valueOf(map.get("pid"))); cell = row.createCell(cellNum++); cell.setCellStyle(cellStyle); cell.setCellValue(null== map.get("price") ? 0.00: Double.parseDouble(String.valueOf(map.get("price")))); cell = row.createCell(cellNum++); cell.setCellStyle(cellStyle); cell.setCellValue(null==map.get("receivernum") ? 0: Integer.parseInt(String.valueOf(map.get("receivernum")))); cell = row.createCell(cellNum++); cell.setCellStyle(cellStyle); cell.setCellValue(null== map.get("allprice") ? 0.00: Double.parseDouble(String.valueOf(map.get("allprice")))); cell = row.createCell(cellNum++); cell.setCellStyle(cellStyle); cell.setCellValue(null== map.get("realallprice") ? 0.00: Double.parseDouble(String.valueOf(map.get("realallprice")))); cell = row.createCell(cellNum++); cell.setCellStyle(cellStyle); cell.setCellValue(null== map.get("remake") ? "": String.valueOf(map.get("remake"))); } public void countReceiveRecordExpressRow(int rowNum ,Row row, CellStyle cellStyle) { Cell cell; cell = row.createCell(0); cell.setCellStyle(cellStyle); cell.setCellValue(rowNum); cell = row.createCell(1); cell.setCellStyle(cellStyle); cell.setCellValue("邮寄邮费"); cell = row.createCell(2); cell.setCellStyle(cellStyle); cell = row.createCell(3); cell.setCellStyle(cellStyle); cell = row.createCell(4); cell.setCellStyle(cellStyle); cell = row.createCell(5); cell.setCellStyle(cellStyle); cell = row.createCell(6); cell.setCellStyle(cellStyle); cell = row.createCell(7); cell.setCellStyle(cellStyle); } public void countReceiveRecordDataToLastRow(double priceAllSum, double discountAllPriceSum, int countNum, Row row, CellStyle cellStyle) { Cell cell; cell = row.createCell(0); cell.setCellStyle(cellStyle); cell = row.createCell(1); cell.setCellStyle(cellStyle); cell.setCellValue("总计"); cell = row.createCell(2); cell.setCellStyle(cellStyle); cell = row.createCell(3); cell.setCellStyle(cellStyle); cell = row.createCell(4); cell.setCellStyle(cellStyle); cell.setCellValue(countNum); cell = row.createCell(5); cell.setCellStyle(cellStyle); cell.setCellValue(priceAllSum); cell = row.createCell(6); cell.setCellStyle(cellStyle); cell.setCellValue(discountAllPriceSum); cell = row.createCell(7); cell.setCellStyle(cellStyle); } private static String convertCellValueToStringKeepDouble(Cell cell) { if (cell == null) { return null; } String returnValue = null; switch (cell.getCellType()) { case Cell.CELL_TYPE_NUMERIC: // 数字 Double doubleValue = cell.getNumericCellValue(); // 格式化科学计数法,取一位整数 DecimalFormat df = new DecimalFormat("#0.00"); returnValue = df.format(doubleValue); break; case Cell.CELL_TYPE_STRING: // 字符串 returnValue = cell.getStringCellValue(); break; case Cell.CELL_TYPE_BOOLEAN: // 布尔 Boolean booleanValue = cell.getBooleanCellValue(); returnValue = booleanValue.toString(); break; case Cell.CELL_TYPE_BLANK: // 空值 break; case Cell.CELL_TYPE_FORMULA: // 公式 returnValue = cell.getCellFormula(); break; case Cell.CELL_TYPE_ERROR: // 故障 break; default: break; } return returnValue; } private static SupplyProduct convertSupplyProductRowToData(Row row) { SupplyProduct supplyProduct = new SupplyProduct(); DecimalFormat numdf = new DecimalFormat("#0.00"); Cell cell; int cellNum = 0; // 获取编码 cell = row.getCell(cellNum++); String isbn = convertCellValueToString(cell); supplyProduct.setIsbn(isbn); // 获取名称 cell = row.getCell(cellNum++); String pname = convertCellValueToString(cell); supplyProduct.setPname(pname); //定价 cell = row.getCell(cellNum++); String price = convertCellValueToStringKeepDouble(cell); supplyProduct.setPrice(price); // 获取折扣 cell = row.getCell(cellNum++); Double discount = cell.getNumericCellValue(); String discount1 = numdf.format(discount); supplyProduct.setDiscount(discount1); // 实际价格 cell = row.getCell(cellNum++); String realprice = String.valueOf(cell.getNumericCellValue()); supplyProduct.setRealPrice(realprice); // 获取单件数量 cell = row.getCell(cellNum++); Integer eachNum = Integer.valueOf(convertCellValueToString(cell)); supplyProduct.setEachNum(eachNum); cell = row.getCell(cellNum++); String supplyName = convertCellValueToString(cell); supplyProduct.setSupplyName(supplyName); return supplyProduct; } private static List
parseSupplyProductExcel(Workbook workbook) { List
resultDataList = new ArrayList<>(); // 解析sheet for (int sheetNum = 0; sheetNum < workbook.getNumberOfSheets(); sheetNum++) { Sheet sheet = workbook.getSheetAt(sheetNum); // 校验sheet是否合法 if (sheet == null) { continue; } // 获取第一行数据 int firstRowNum = sheet.getFirstRowNum(); Row firstRow = sheet.getRow(firstRowNum); if (null == firstRow) { log.info("解析Excel失败,在第一行没有读取到任何数据!"); } // 解析每一行的数据,构造数据对象 int rowStart = firstRowNum + 1; int rowEnd = sheet.getPhysicalNumberOfRows(); for (int rowNum = rowStart; rowNum < rowEnd; rowNum++) { Row row = sheet.getRow(rowNum); if (null == row) { continue; } SupplyProduct resultData = convertSupplyProductRowToData(row); if (null == resultData) { log.info("第 " + row.getRowNum() + "行数据不合法,已忽略!"); continue; } resultDataList.add(resultData); } } return resultDataList; } public static List
readSupplyProductExcel(InputStream inputStream,String fileType) { Workbook workbook = null; try { workbook = getWorkbook(inputStream, fileType); // 读取excel中的数据 List
resultDataList = parseSupplyProductExcel(workbook); return resultDataList; } catch (Exception e) { log.info("解析Excel失败! 错误信息:" + e.getMessage()); return null; } finally { try { if (null != inputStream) { inputStream.close(); } } catch (Exception e) { log.info("关闭数据流出错!错误信息:" + e.getMessage()); return null; } } } public void uploadSupplyProductExcel( User user,MultipartFile mFile) throws Exception { if (mFile == null) { throw new Exception("请选择上传文件"); } if (mFile.isEmpty()) { throw new Exception("不允许上传空文件"); } SimpleDateFormat sdf = new SimpleDateFormat("yyyy_MM_dd"); String dateDir = sdf.format(new Date()); File fileDir = new File(cservice.getConstant("supplyproductexcelpath") + dateDir); // 判定目录是否存在,不存在则创建 if (!fileDir.exists()){ fileDir.mkdirs(); } // 构建文件对象(fileDir为目录,mFile.getOriginalFilename()文件名) String fileName = mFile.getOriginalFilename(); File dest = new File(fileDir, fileName); mFile.transferTo(dest); //读取数据 InputStream inputStream = mFile.getInputStream(); String fileType = fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length()); List
list = readSupplyProductExcel(inputStream, fileType); int t = 0; if(list!=null && list.size()>0){ for (int i = 0; i < list.size(); i++) { SupplyProduct product = list.get(i); String supplyName = String.valueOf(product.getSupplyName()); List
> result = pdao.querySupplyByName(supplyName); if (result!=null && result.size()>0) { i++; String supplyId = String.valueOf(result.get(0).get("id")); product.setSupplyId(supplyId); pservice.insertAndUpdateSupplyProduct(list.get(i)); }else{ log.info("没有找到 供应商: "+supplyName); } } }else{ log.info("供应商书目文件上传失败:没有获取到数据"); throw new UploadDownloadException(fileName); } if(t==0){ throw new UploadDownloadException("没有匹配供应商"); } } // public static void main(String[] args) {// ExcelService es = new ExcelService();// BaseDAO dao = new BaseDAO();// String sql = " select * from taobao.t_express where `sdtime` > '2020-09-13' ";// List
> query = dao.query(sql, "stock");// es.createWoDaExcel(query);// } public static void main(String[] args) throws InterruptedException { CloudPrintManager cpm = CloudPrintManager.getDefault(); Workbook workbook = null; FileInputStream inputStream = null; List
nameList = new ArrayList
(); List
codeList = new ArrayList
(); List
bookshelfList = new ArrayList
(); try { inputStream = new FileInputStream(new File("/Volumes/disksd/work/test/test888.xlsx")); workbook = getWorkbook(inputStream, XLSX); // 解析sheet for (int sheetNum = 0; sheetNum < workbook.getNumberOfSheets(); sheetNum++) { Sheet sheet = workbook.getSheetAt(sheetNum); // 校验sheet是否合法 if (sheet == null) { continue; } // 获取第一行数据 int firstRowNum = sheet.getFirstRowNum(); Row firstRow = sheet.getRow(firstRowNum); if (null == firstRow) { log.info("解析Excel失败,在第一行没有读取到任何数据!"); } // 解析每一行的数据,构造数据对象 int rowStart = firstRowNum ; int rowEnd = sheet.getPhysicalNumberOfRows(); for (int rowNum = rowStart; rowNum < rowEnd; rowNum++) { Row row = sheet.getRow(rowNum); if (null == row) { continue; } Cell cell; int cellNum = 0; // 获取编码 cell = row.getCell(cellNum++); String name = convertCellValueToString(cell); nameList.add(name); // 获取名称 cell = row.getCell(cellNum++); String code = convertCellValueToString(cell); codeList.add(code); // 获取书架 cell = row.getCell(cellNum++); String bookshelf = convertCellValueToString(cell); bookshelfList.add(bookshelf); } } } catch (Exception e) { log.info("解析Excel失败! 错误信息:" + e.getMessage()); } finally { try { if (null != inputStream) { inputStream.close(); } } catch (Exception e) { log.info("关闭数据流出错!错误信息:" + e.getMessage()); } } for (int i = 0; i < codeList.size(); i++) { cpm.printLabel(codeList.get(i), bookshelfList.get(i)); Thread.sleep(1000); } }}
@RequestMapping("/uploadaddSeriesExcel")    @ResponseBody    public String getExcelData(MultipartFile file) throws IOException {    	System.out.println("进来了");       Map
map = new HashMap<>(); map.put("data", AnalysisExcelData.getExcelData(file)); System.out.println(AnalysisExcelData.getExcelData(file)); System.out.println(map); return json(map); }
  • 是否解锁
上一篇:MATLAB 修改启动路径
下一篇:ajax 传递数组的关键

发表评论

最新留言

做的很好,不错不错
[***.243.131.199]2025年04月03日 07时39分50秒