ExcelTemplateUtil.java 3.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. package com.minpay.common.util;
  2. import org.apache.commons.fileupload.FileItem;
  3. import org.apache.poi.hssf.usermodel.HSSFWorkbook;
  4. import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
  5. import org.apache.poi.ss.usermodel.*;
  6. import org.apache.poi.xssf.usermodel.XSSFWorkbook;
  7. import java.io.IOException;
  8. import java.io.InputStream;
  9. import java.util.ArrayList;
  10. import java.util.HashMap;
  11. import java.util.List;
  12. import java.util.Map;
  13. /**
  14. * Excel导入模板校验
  15. */
  16. public class ExcelTemplateUtil {
  17. /**
  18. * 验证表头数据
  19. * @param excel
  20. * @param header
  21. * @return
  22. */
  23. public static boolean verificationExcelHeadLine(FileItem excel, Map<String,Object> header) throws IOException, InvalidFormatException {
  24. boolean flag = true;
  25. List<String[]> list = (List<String[]>) header.get("header");
  26. Workbook wb = WorkbookFactory.create(excel.getInputStream());
  27. String fileName = excel.getName();
  28. Workbook hssfWorkbook = null;
  29. if (fileName.endsWith(".xlsx") ){
  30. hssfWorkbook = new XSSFWorkbook(excel.getInputStream());//Excel 2007
  31. }else if(fileName.endsWith(".xls")){
  32. hssfWorkbook = new HSSFWorkbook(excel.getInputStream());//Excel 2003
  33. }
  34. int numSheets = 0;//hssfWorkbook.getNumberOfSheets();
  35. List<String[]> listWK = new ArrayList<String[]>();
  36. //取所有sheet页的表头
  37. if ( numSheets == 0) {
  38. flag = false;
  39. } else {
  40. Map<String,List<String[]>> temp = new HashMap<String,List<String[]>>();
  41. for (int numSheet = 0; numSheet < numSheets; numSheet++) {//遍历Sheet
  42. Sheet hssfSheet = hssfWorkbook.getSheetAt(numSheet);
  43. if (hssfSheet == null) {
  44. continue;
  45. }
  46. int rows = StringUtil.ObjToInt(header.get("headerRows"));
  47. // 循环行Row
  48. for (int rowNum = 0; rowNum <= rows; rowNum++) {//遍历行
  49. int cols = StringUtil.ObjToInt(header.get("cols"));
  50. String[] colsValue = new String[cols];
  51. Row hssfRow = hssfSheet.getRow(rowNum);
  52. if (hssfRow != null) {
  53. for (int cloNum = 0; cloNum < cols; cloNum++){//遍历列
  54. Cell value = hssfRow.getCell(cloNum);
  55. colsValue[cloNum] = StringUtil.ObjectToString(value);
  56. }
  57. }
  58. listWK.add(colsValue);
  59. }
  60. }
  61. }
  62. //比对表头,如果不一致则表示模板不一致,校验失败
  63. String[] excelheader = list.get(list.size() - 1);
  64. String[] excelheader2 = listWK.get(listWK.size() - 1);
  65. if(excelheader.length != excelheader2.length){
  66. flag = false;
  67. } else {
  68. for (int i = 0; i < excelheader.length; i++) {
  69. if(!excelheader[i].equals(excelheader2[i])){
  70. flag = false;
  71. break;
  72. }
  73. }
  74. }
  75. return flag;
  76. }
  77. }