zoukankan      html  css  js  c++  java
  • java使用Apache POI 读取excel文件

    1.导入包

    <dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-ooxml</artifactId>
    <version>3.11-beta1</version>
    </dependency>

    2.mapper映射文件批量插入
     <insert id="insertStudentlist" parameterType="java.util.List">
    insert into student_table(studentname, studenage, studentsex) values
    <foreach collection="list" index="index" item="item" separator=",">
    (#{item.studentname,jdbcType=VARCHAR}, #{item.studenage,jdbcType=VARCHAR}, #{item.studentsex,jdbcType=VARCHAR})
    </foreach>
    </insert>
    3.dao层
    //批量添加学生信息
    public int insertStudentlist(List<User>userlist);

    4.service层
    public int insertStudentlist(List<User> userlist) ;
    5.实现service层
    public int insertStudentlist(List<User> userlist) {
    // TODO Auto-generated method stub
    int count=Userdao.insertStudentlist(userlist);
    return count;
    }

    6.controller
    @RequestMapping(value="/fileUpload")
    public String fileUpload(@RequestParam("file") MutipartFile file)throws
    IOException,InvalidFormatException{

       if(!file.isEmpty()){  //判断文件是否为空

         try{

          //文件保存路径    file.getOriginaFilename()获取原上传文件的名称

          String file = request.getSession().getServletContext().getRealPath("/")+"upload"+file.getOriginaFilename();  

          file.transferTo(new File(filePath));

          File f1 = new File(filePath.replace("\",''/"));

          String jsonstr = ExcelTool.readExcel(f1).toString();

          List<User> userlist = JSON.parseArray(jsonstr.User.class);

          Integer order;

          for(int i = 0;i<userlist.size();i++){

            order = i+1;

            userlist.get(i).setOrder(order.toString());

            if(userlist.get(i).getStudentsex().equals("男")){

              userlist.get(i).setStudentsex("1")

            }else{

              userlist.get(i).setStudentsex("2")

            }

          }

          userService.insertStudentlist(userlist);

        }catch(Exception e){

          e.printStackTrace();

        }

      }

      
    return "redirect:/index.jsp";
    }


    public static JSONArray readExcel(File file) throws FileNotFoundException, IOException, InvalidFormatException{
       int res = checkFile(file);
    if (res == 0) {
    throw new NullPointerException("the file is null.");
    }else if (res == 1) {
    return readXLSX(file);
      }else if (res == 2) {
    return readXLS(file);
    }
    throw new IllegalAccessError("the file["+file.getName()+"] is not excel file.");
    }


    public static int checkFile(File file){
    if (file==null) {
    return 0;
      }
      String flieName = file.getName();
    if (flieName.endsWith(XLSX)) {
    return 1;
       }
    if (flieName.endsWith(XLS)) {
    return 2;
      }
      return 3;
    }

    public static JSONArray readXLSX(File file) throws InvalidFormatException, IOException{
    Workbook book = new XSSFWorkbook(file); //得到文档对象,用xssf对象来解析xlsx文件
    Sheet sheet = book.getSheetAt(0); //获取第一个表单
    return read(sheet, book);
    }

    public static JSONArray readXLS(File file) throws FileNotFoundException, IOException{
    POIFSFileSystem poifsFileSystem = new POIFSFileSystem(new FileInputStream(file));
    Workbook book = new HSSFWorkbook(poifsFileSystem); //用Hssf来解析xls格式的文件
    Sheet sheet = book.getSheetAt(0);
    return read(sheet, book);
    }
    public static JSONArray read(Sheet sheet,Workbook book) throws IOException{
    int rowStart = sheet.getFirstRowNum(); // 首行下标
    int rowEnd = sheet.getLastRowNum(); // 尾行下标
    // 如果首行与尾行相同,表明只有名称,直接返回空数组
    if (rowStart == rowEnd) {
    book.close();
    return new JSONArray();
    }
    // 获取第一行JSON对象?
    Row firstRow = sheet.getRow(rowStart);
    int cellStart = firstRow.getFirstCellNum();
    int cellEnd = firstRow.getLastCellNum();
      Map<Integer, String> keyMap = new HashMap<Integer, String>();
    for (int j = cellStart; j < cellEnd; j++) {
    keyMap.put(j,getValue(firstRow.getCell(j), rowStart, j, book, true));
      }
    // 获取每行JSON对象
    JSONArray array = new JSONArray();
    for(int i = rowStart+1; i <= rowEnd ; i++) {
    Row eachRow = sheet.getRow(i);
    JSONObject obj = new JSONObject();
    StringBuffer sb = new StringBuffer();
    for (int k = cellStart; k < cellEnd; k++) {
    if (eachRow != null) {
    String val = getValue(eachRow.getCell(k), i, k, book, false);
    sb.append(val);
           obj.put(keyMap.get(k),val);

           }
    }
    if (sb.toString().length() > 0) {
    array.add(obj);

        }
    }
    book.close();
    return array;
    }



    public static String getValue(Cell cell,int rowNum,int index,Workbook book,boolean isKey) throws IOException{
    // 空白或空
    if (cell == null || cell.getCellType()==Cell.CELL_TYPE_BLANK ) {
    if (isKey) {
    book.close();
    throw new NullPointerException(String.format("the key on row %s index %s is null ", ++rowNum,++index));
    }else{
       return "";
    }
    }
    // 0. 数字 类型
    if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC) {
    if (HSSFDateUtil.isCellDateFormatted(cell)) {
    Date date = cell.getDateCellValue();
    DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    return df.format(date);
    }
    String val = cell.getNumericCellValue()+"";
    val = val.toUpperCase();
    if (val.contains("E")) {
    val = val.split("E")[0].replace(".", "");
        }
    return val;
    }
    // 1. String类型
    if (cell.getCellType() == Cell.CELL_TYPE_STRING) {
    String val = cell.getStringCellValue();
    if (val == null || val.trim().length()==0) {
    if (book != null) {
    book.close();
    }
    return "";
    }
    return val.trim();
    }
    // 2. 公式 CELL_TYPE_FORMULA
    if (cell.getCellType() == Cell.CELL_TYPE_FORMULA) {
    return cell.getStringCellValue();
    }
    // 4. 布尔类型CELL_TYPE_BOOLEAN
    if (cell.getCellType() == Cell.CELL_TYPE_BOOLEAN) {
    return cell.getBooleanCellValue()+"";
    }
    // 5. 错误 CELL_TYPE_ERROR
    return "";
    }


    model:
    private String studentname;
    private String studentsex;
    private String studenage;
    priavte String order;
    
    
    
    
    
    
    
    
    
    
    
    
    
    
     
    
    
  • 相关阅读:
    Python 第四十九章 css 补充
    Python 第四十八章 css样式
    Python 第四十七章 css介绍
    iOS 流媒体 基本使用 和方法注意
    iOS 展示 gif
    iOS UIImage UIImageView 展示图片 不变形 处理
    UIImageView 获取图片的 宽 高
    iOS tabbar 上面更换任意图
    iOS 屏幕原点坐标 && 导航栏风格的自定义
    iOS NSDateFormatter 不安全线程 处理
  • 原文地址:https://www.cnblogs.com/libo199374/p/8341643.html
Copyright © 2011-2022 走看看