excel文件导入(xls,xlsx)

时间:2022-04-09 14:02:50
java导入excel数据分析:
 
 提出问题:excel导入数据?

 分析问题
  1.excel有那几种格式
   xls,xlsx
  2.如何将excel导入,转换成java中的数据类型
   (我们这里是将表格中的数据转化成:Map<Integer, Map<Integer, List<String>>>)
    
 解决问题

       1.(注意:xls格式的数据必须使用poi导入使用的工具类ExcelSwitchMap;
            xlsx格式的数据必须使用poi导入使用的工具类ExcelSwitchMap;
        )

       步骤
       1.
        准备相应的poi jar
        pom(自行百度,网上有讲)

       2.从前台到后端
        前台:
        html:
        <input type="button"  value="导入表格" id="submitBtn"    onclick="importExcel(this)"    class="btn btn-primary btn-mini"/>

        js:
         function importExcel(e) {
    $(e).attr("disabled", true);
    if ($("#uploadFileData").val().length > 0) {
     //开始文件导入
     var nwOfficeId = $('#uploadFileData').val();
     $.ajaxFileUpload({
        url : '<%=WEBPATH%>/factIndMat/factIndMateInput',//需要链接到服务器地址
                 secureuri:false,
                 fileElementId:'uploadFileData',
                 dataType: 'text',  //服务器返回的格式,可以是json
                 success: function (data, status) {
                    window.location.reload();//刷新当前页面.
                  alert(data);
                  $(e).attr("disabled", false);
                  
                 },
                 error: function (status){
                  alert("导入失败!");
                  $(e).attr("disabled", false);
                 }
               });
          }  
          else {  
     $("#submitBtn").val('导入表格');
              alert("请选择文件!");  
     $(e).attr("disabled", false);  
          }  
   }
   controller:

   @RequestMapping(value = "/factIndMateInput", produces = "text/html;charset=UTF-8")
 @ResponseBody
 public String factIndMateInput(HttpServletRequest request, HttpSession session) {
  UserInfoVO loginUser = (UserInfoVO) session.getAttribute(SessionConstants.LOGIN_SESSION_ID);
  FactInfoVO fact = factIndMatService.findFactInfoByUserId(loginUser.getUserId());
  String model = "";
  try {
   MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
   CommonsMultipartFile file = (CommonsMultipartFile) multipartRequest.getFile("uploadFile");
   String theFileName = file.getFileItem().getName().toString();
   Map<Integer, Map<Integer, List<String>>> map = null;
   String theFormat = theFileName.substring(theFileName.indexOf("."), theFileName.length());
   // 判断文件格式【xls;xlsx】
   if (".xls".equals(theFormat)) {
    // xls:需要用到poi
    POIFSFileSystem in = new POIFSFileSystem(file.getInputStream());
    map = ExcelSwitchMap.getExcel(in, 8);
   } else {
    map = ExcelSwitchMapData.readExcelData(file.getInputStream());
   }
   Map<Integer, List<String>> dataMap = map.get(0);

   String bool = factIndMatService.importFIMData(dataMap, 2, fact.getFactid(), loginUser);
   if (bool.equals("导入成功")) {
    model = "导入成功";
   } else {
    model = "导入失败";
   }
   if (model.equals("导入失败")) {
    model = factIndMatService.getDataInputMsg() + ",请重新填写!";
   }
  } catch (Exception e) {
   e.printStackTrace();
   model = factIndMatService.getDataInputMsg();
  }

  return model;
 }


  工具类1: ExcelSwitchMap(poi:xls)
注意参数:POIFSFileSystem  ,所导入excel的列数
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

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.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;

public class ExcelSwitchMap {
 /***
  *
  * @param in   POIFSFileSystem
  * @param max  所导入excel的列数
  * @return map
  * @throws IOException
  */
 @SuppressWarnings({ "deprecation", "resource" })
 public static Map<Integer, Map<Integer, List<String>>> getExcel(POIFSFileSystem in,int max)
   throws IOException {
  Map<Integer, Map<Integer, List<String>>> map = new HashMap<Integer, Map<Integer, List<String>>>();// 总map
  Map<Integer, List<String>> sheetMap = null;// 每个sheet的map
  List<String> list = null;// 每行一个list
  HSSFWorkbook workBook = null;
  try {
   workBook = new HSSFWorkbook(in);
  } catch (final Exception e) {
   throw new IOException("读取上传文件失败");
  }
  /**
   * 获得Excel中工作表个数
   */
  // sheet.autoSizeColumn(( short ) 0 );//导出自动适应宽度
  int sheetSize = workBook.getNumberOfSheets();
//  System.out.println("工作表个数 :" + sheetSize);
  for (int i = 0; i < sheetSize; i++) {
   sheetMap = new HashMap<Integer, List<String>>();
//   System.out.println("工作表名称:" + workBook.getSheetName(i));
   HSSFSheet sheet = workBook.getSheetAt(i);
   int rows = sheet.getPhysicalNumberOfRows(); // 获得行数
   if (rows > 0) {
    for (int j = 0; j < rows; j++) { // 行循环
     list = new ArrayList<String>();
     HSSFRow row = sheet.getRow(j);
     if (row != null) {
      int cells = row.getLastCellNum();// 获得列数
      if(cells<max){
       cells = max;
      }
      for (short k = 0; k < cells; k++) { // 列循环
       HSSFCell cell = row.getCell(k);
       String value = "";
       if(cell != null){
        switch (cell.getCellType()) {
        case HSSFCell.CELL_TYPE_NUMERIC: // 数值型
         if (HSSFDateUtil.isCellDateFormatted(cell)) {
          // 如果是date类型则 ,获取该cell的date值
          value = HSSFDateUtil.getJavaDate(
            cell.getNumericCellValue())
            .toString();
         } else {// 纯数字
          value = String.valueOf(cell
            .getNumericCellValue());
         }
         if(value.matches("^((\\d+\\.?\\d+)[Ee]{1}(\\d+)){1}")){
          DecimalFormat df = new DecimalFormat("#.##");
          value = df.format(Double.parseDouble(value));
         }
         break;
        case HSSFCell.CELL_TYPE_STRING: // 字符串型
         value = cell.getRichStringCellValue()
           .toString().trim();
         break;
        case HSSFCell.CELL_TYPE_FORMULA:// 公式型
         // 读公式计算值
         value = String.valueOf(cell
           .getNumericCellValue());
         if (value.equals("NaN")) {// 如果获取的数据值为非法值,则转换为获取字符串
          value = cell.getRichStringCellValue()
            .toString();
         }
         break;
        case HSSFCell.CELL_TYPE_BOOLEAN:// 布尔
         value = "" + cell.getBooleanCellValue();
         break;
        /* 此行表示该单元格值为空 */
        case HSSFCell.CELL_TYPE_BLANK: // 空值
         value = "";
         break;
        case HSSFCell.CELL_TYPE_ERROR: // 故障
         value = "";
         break;
        default:
         value = cell.getRichStringCellValue()
           .toString().trim();
        }
       }
       list.add(value);
      }
      if(!isAllNull(list)){
       sheetMap.put(j, list);
      }
     }
    }
   }
   map.put(i, sheetMap);
  }
  return map;
 }
 /**
  * 如果list里面的值全为空 则范围true 反之则为false
  * @param l list
  * @return
  */
 private static boolean isAllNull(List<String> l){
  int i=0;
  for(String s : l){
   if(!"".equals(s)){
    i++;
   }
  }
  if(i>0){
   return false;
  }
  return true;
 }
 
 public static void main(String[] args) {
  String filePath = "d:/template.xls";
  try {
   POIFSFileSystem fs = new POIFSFileSystem(new FileInputStream(filePath));
   Map<Integer, Map<Integer, List<String>>> map = getExcel(fs,9);
   for(Entry<Integer, List<String>> ent : map.get(0).entrySet()){
    System.out.println(ent);
   }
  } catch (FileNotFoundException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
 }
}

工具类2:ExcelSwitchMapData(注意参数:InputStream)
 
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class ExcelSwitchMapData {
 public static Map<Integer, Map<Integer, List<String>>> readExcelData(InputStream dataIn) throws IOException {
        InputStream is = dataIn;

        @SuppressWarnings("resource")
        XSSFWorkbook wb = new XSSFWorkbook(is);

        XSSFSheet sheet = wb.getSheetAt(0); // 获取第一个sheet表
        XSSFRow rowData;
        Map<Integer, Map<Integer, List<String>>> resultData = new HashMap<Integer, Map<Integer, List<String>>>();
        Map<Integer, List<String>>  theRowMap = new HashMap<Integer, List<String>>();
        List<String> list = null;
        String columValue;

        for (int i = 0; i < sheet.getLastRowNum() + 1; i++) {
         //行循环
            rowData = sheet.getRow(i);
         list = new ArrayList<String>();
            for (int j = rowData.getFirstCellNum(); j < rowData.getLastCellNum(); j++) {
             //列循环
            
             columValue = rowData.getCell(j).toString();
                list.add(columValue);
            }
            theRowMap.put(i, list);
        }

        is.close();
        resultData.put(0, theRowMap);
        return resultData;
    }
 public static void main(String[] args) {
  /*try {
    Map<Integer, Map<Integer, List<String>>> data = ExcelSwitchMapData.readExcelData("C:\\Users\\wupeng\\Downloads\\xxxDemo.xlsx");
     Map<Integer, List<String>>  theRowMap = data.get(0);
     Iterator<Entry<Integer, List<String>>> itNext = theRowMap.entrySet().iterator();
     while (itNext.hasNext()) {
       Entry<Integer, List<String>> entry = itNext.next();
       System.out.println("key= " + entry.getKey() + " and value= " + entry.getValue());
     }
  } catch (IOException e) {
   e.printStackTrace();
  }*/
 }
}
  
  附加:

  如果遍历传进来的参数:
  Map<Integer, List<String>> map = new HashMap<Integer, List<String>>();
  for (Entry<Integer, List<String>> ent : map.entrySet()) {
   
    IndMateVO indMate = new IndMateVO();
    //startIndex:表示从第二行读取exel 中的数据
    if (ent.getKey() >= startIndex - 1) {
    }
  }


总结
 1.解析excel中导入的文件

 2.判断它的格式:xls ,xlsx
 3.使用不同的工具类(xls(poi) : ExcelSwitchMap.java   ; xlsx :ExcelSwitchMapData.java )
  将不同的excel数据转化成java中的数据类型:map  或者list
 
   4.分析map  或  list 中的数据 ,然后进行处理