poi导出Excel Java POI导入导出Excel

Java POI导入导出Excel

 

1、异常java.lang.NoClassDefFoundError: org/apache/poi/UnsupportedFileFormatException

  解决方法:

    使用的poi的相关jar包一定版本一定要相同!!!!!


2、maven所使用jar包,没有使用maven的话,就用poi-3.9.jar和poi-ooxml-3.9.jar(这个主要是用于Excel2007以后的版本)两个jar包就行()

复制代码
       <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>3.9</version>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>3.9</version>
        </dependency>
复制代码

3、java导入Excel

    先上传Excel
    

复制代码
//上传Excel
    @RequestMapping("/uploadExcel")
    public boolean uploadExcel(@RequestParam MultipartFile file,HttpServletRequest request) throws IOException {

        if(!file.isEmpty()){
            String filePath = file.getOriginalFilename();
            //windows
            String savePath = request.getSession().getServletContext().getRealPath(filePath);

            //linux
            //String savePath = "/home/odcuser/webapps/file";

            File targetFile = new File(savePath);

            if(!targetFile.exists()){
                targetFile.mkdirs();
            }

            file.transferTo(targetFile);
            return true;
        }

        return false;
    }
复制代码

  在读取Excel里面的内容

    

复制代码
 public static void readExcel() throws Exception{


        InputStream is = new FileInputStream(new File(fileName));
        Workbook hssfWorkbook = null;
        if (fileName.endsWith("xlsx")){
           hssfWorkbook = new XSSFWorkbook(is);//Excel 2007
        }else if (fileName.endsWith("xls")){
            hssfWorkbook = new HSSFWorkbook(is);//Excel 2003

        }
       // HSSFWorkbook hssfWorkbook = new HSSFWorkbook(is);
       // XSSFWorkbook hssfWorkbook = new XSSFWorkbook(is);
        User student = null;
        List<User> list = new ArrayList<User>();
        // 循环工作表Sheet
        for (int numSheet = 0; numSheet <hssfWorkbook.getNumberOfSheets(); numSheet++) {
            //HSSFSheet hssfSheet = hssfWorkbook.getSheetAt(numSheet);
            Sheet hssfSheet = hssfWorkbook.getSheetAt(numSheet);
            if (hssfSheet == null) {
                continue;
            }
            // 循环行Row
            for (int rowNum = 1; rowNum <= hssfSheet.getLastRowNum(); rowNum++) {
                //HSSFRow hssfRow = hssfSheet.getRow(rowNum);
                Row hssfRow = hssfSheet.getRow(rowNum);
                if (hssfRow != null) {
                    student = new User();
                    //HSSFCell name = hssfRow.getCell(0);
                    //HSSFCell pwd = hssfRow.getCell(1);
                    Cell name = hssfRow.getCell(0);
                    Cell pwd = hssfRow.getCell(1);
//这里是自己的逻辑
                    student.setUserName(name.toString());
                    student.setPassword(pwd.toString());

                    list.add(student);
                }
            }
        }


    }
复制代码

4、导出Excel

  

复制代码
 //创建Excel
    @RequestMapping("/createExcel")
    public String createExcel(HttpServletResponse response) throws IOException {

        //创建HSSFWorkbook对象(excel的文档对象)
        HSSFWorkbook wb = new HSSFWorkbook();
//建立新的sheet对象(excel的表单)
        HSSFSheet sheet=wb.createSheet("成绩表");
//在sheet里创建第一行,参数为行索引(excel的行),可以是0~65535之间的任何一个
        HSSFRow row1=sheet.createRow(0);
//创建单元格(excel的单元格,参数为列索引,可以是0~255之间的任何一个
        HSSFCell cell=row1.createCell(0);
        //设置单元格内容
        cell.setCellValue("学员考试成绩一览表");
//合并单元格CellRangeAddress构造参数依次表示起始行,截至行,起始列, 截至列
        sheet.addMergedRegion(new CellRangeAddress(0,0,0,3));
//在sheet里创建第二行
        HSSFRow row2=sheet.createRow(1);
        //创建单元格并设置单元格内容
        row2.createCell(0).setCellValue("姓名");
        row2.createCell(1).setCellValue("班级");
        row2.createCell(2).setCellValue("笔试成绩");
        row2.createCell(3).setCellValue("机试成绩");
        //在sheet里创建第三行
        HSSFRow row3=sheet.createRow(2);
        row3.createCell(0).setCellValue("李明");
        row3.createCell(1).setCellValue("As178");
        row3.createCell(2).setCellValue(87);
        row3.createCell(3).setCellValue(78);
        //.....省略部分代码


//输出Excel文件
        OutputStream output=response.getOutputStream();
        response.reset();
        response.setHeader("Content-disposition", "attachment; filename=details.xls");
        response.setContentType("application/msexcel");
        wb.write(output);
        output.close();
        return null;
    }
复制代码

补充说明乱码问题

  1、文件名乱码(我发现只要解决了文件名乱码,其他乱码也会跟着解决)response.setHeader("Content-disposition", "attachment; filename=中文.xls");

  这个方法可以当做一个公用方法来使用,以后有乱码的都可以调用此方法

复制代码
public static String toUtf8String(String s){ 
     StringBuffer sb = new StringBuffer(); 
       for (int i=0;i<s.length();i++){ 
          char c = s.charAt(i); 
          if (c >= 0 && c <= 255){sb.append(c);} 
        else{ 
        byte[] b; 
         try { b = Character.toString(c).getBytes("utf-8");} 
         catch (Exception ex) { 
             System.out.println(ex); 
                  b = new byte[0]; 
         } 
            for (int j = 0; j < b.length; j++) { 
             int k = b[j]; 
              if (k < 0) k += 256; 
              sb.append("%" + Integer.toHexString(k).toUpperCase()); 
              } 
     } 
  } 
  return sb.toString(); 
}
复制代码

  调用的时候,response.setHeader("Content-disposition", "attachment; filename="+toUtf8String("中文.xls"));

  我上网查的时候,网上是说

    今天要说的是在创建工作表时,用中文做文件名和工作表名会出现乱码的问题,先说以中文作为工作表名,大家创建工作表的代码一般如下:

        HSSFWorkbook workbook = new HSSFWorkbook();//创建EXCEL文件

        HSSFSheet  sheet= workbook.createSheet(sheetName);    //创建工作表

      这样在用英文名作为工作表名是没问题的,但如果sheetName是中文字符,就会出现乱码,解决的方法如下代码:

  
     HSSFSheet  sheet= workbook.createSheet();

     workbook.setSheetName(0, sheetName,(short)1); //这里(short)1是解决中文乱码的关键;而第一个参数是工作表的索引号。

1、异常java.lang.NoClassDefFoundError: org/apache/poi/UnsupportedFileFormatException

  解决方法:

    使用的poi的相关jar包一定版本一定要相同!!!!!


2、maven所使用jar包,没有使用maven的话,就用poi-3.9.jar和poi-ooxml-3.9.jar(这个主要是用于Excel2007以后的版本)两个jar包就行()

复制代码
       <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>3.9</version>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>3.9</version>
        </dependency>
复制代码

3、java导入Excel

    先上传Excel
    

复制代码
//上传Excel
    @RequestMapping("/uploadExcel")
    public boolean uploadExcel(@RequestParam MultipartFile file,HttpServletRequest request) throws IOException {

        if(!file.isEmpty()){
            String filePath = file.getOriginalFilename();
            //windows
            String savePath = request.getSession().getServletContext().getRealPath(filePath);

            //linux
            //String savePath = "/home/odcuser/webapps/file";

            File targetFile = new File(savePath);

            if(!targetFile.exists()){
                targetFile.mkdirs();
            }

            file.transferTo(targetFile);
            return true;
        }

        return false;
    }
复制代码

  在读取Excel里面的内容

    

复制代码
 public static void readExcel() throws Exception{


        InputStream is = new FileInputStream(new File(fileName));
        Workbook hssfWorkbook = null;
        if (fileName.endsWith("xlsx")){
           hssfWorkbook = new XSSFWorkbook(is);//Excel 2007
        }else if (fileName.endsWith("xls")){
            hssfWorkbook = new HSSFWorkbook(is);//Excel 2003

        }
       // HSSFWorkbook hssfWorkbook = new HSSFWorkbook(is);
       // XSSFWorkbook hssfWorkbook = new XSSFWorkbook(is);
        User student = null;
        List<User> list = new ArrayList<User>();
        // 循环工作表Sheet
        for (int numSheet = 0; numSheet <hssfWorkbook.getNumberOfSheets(); numSheet++) {
            //HSSFSheet hssfSheet = hssfWorkbook.getSheetAt(numSheet);
            Sheet hssfSheet = hssfWorkbook.getSheetAt(numSheet);
            if (hssfSheet == null) {
                continue;
            }
            // 循环行Row
            for (int rowNum = 1; rowNum <= hssfSheet.getLastRowNum(); rowNum++) {
                //HSSFRow hssfRow = hssfSheet.getRow(rowNum);
                Row hssfRow = hssfSheet.getRow(rowNum);
                if (hssfRow != null) {
                    student = new User();
                    //HSSFCell name = hssfRow.getCell(0);
                    //HSSFCell pwd = hssfRow.getCell(1);
                    Cell name = hssfRow.getCell(0);
                    Cell pwd = hssfRow.getCell(1);
//这里是自己的逻辑
                    student.setUserName(name.toString());
                    student.setPassword(pwd.toString());

                    list.add(student);
                }
            }
        }


    }
复制代码

4、导出Excel

  

复制代码
 //创建Excel
    @RequestMapping("/createExcel")
    public String createExcel(HttpServletResponse response) throws IOException {

        //创建HSSFWorkbook对象(excel的文档对象)
        HSSFWorkbook wb = new HSSFWorkbook();
//建立新的sheet对象(excel的表单)
        HSSFSheet sheet=wb.createSheet("成绩表");
//在sheet里创建第一行,参数为行索引(excel的行),可以是0~65535之间的任何一个
        HSSFRow row1=sheet.createRow(0);
//创建单元格(excel的单元格,参数为列索引,可以是0~255之间的任何一个
        HSSFCell cell=row1.createCell(0);
        //设置单元格内容
        cell.setCellValue("学员考试成绩一览表");
//合并单元格CellRangeAddress构造参数依次表示起始行,截至行,起始列, 截至列
        sheet.addMergedRegion(new CellRangeAddress(0,0,0,3));
//在sheet里创建第二行
        HSSFRow row2=sheet.createRow(1);
        //创建单元格并设置单元格内容
        row2.createCell(0).setCellValue("姓名");
        row2.createCell(1).setCellValue("班级");
        row2.createCell(2).setCellValue("笔试成绩");
        row2.createCell(3).setCellValue("机试成绩");
        //在sheet里创建第三行
        HSSFRow row3=sheet.createRow(2);
        row3.createCell(0).setCellValue("李明");
        row3.createCell(1).setCellValue("As178");
        row3.createCell(2).setCellValue(87);
        row3.createCell(3).setCellValue(78);
        //.....省略部分代码


//输出Excel文件
        OutputStream output=response.getOutputStream();
        response.reset();
        response.setHeader("Content-disposition", "attachment; filename=details.xls");
        response.setContentType("application/msexcel");
        wb.write(output);
        output.close();
        return null;
    }
复制代码

补充说明乱码问题

  1、文件名乱码(我发现只要解决了文件名乱码,其他乱码也会跟着解决)response.setHeader("Content-disposition", "attachment; filename=中文.xls");

  这个方法可以当做一个公用方法来使用,以后有乱码的都可以调用此方法

复制代码
public static String toUtf8String(String s){ 
     StringBuffer sb = new StringBuffer(); 
       for (int i=0;i<s.length();i++){ 
          char c = s.charAt(i); 
          if (c >= 0 && c <= 255){sb.append(c);} 
        else{ 
        byte[] b; 
         try { b = Character.toString(c).getBytes("utf-8");} 
         catch (Exception ex) { 
             System.out.println(ex); 
                  b = new byte[0]; 
         } 
            for (int j = 0; j < b.length; j++) { 
             int k = b[j]; 
              if (k < 0) k += 256; 
              sb.append("%" + Integer.toHexString(k).toUpperCase()); 
              } 
     } 
  } 
  return sb.toString(); 
}
复制代码

  调用的时候,response.setHeader("Content-disposition", "attachment; filename="+toUtf8String("中文.xls"));

  我上网查的时候,网上是说

    今天要说的是在创建工作表时,用中文做文件名和工作表名会出现乱码的问题,先说以中文作为工作表名,大家创建工作表的代码一般如下:

        HSSFWorkbook workbook = new HSSFWorkbook();//创建EXCEL文件

        HSSFSheet  sheet= workbook.createSheet(sheetName);    //创建工作表

      这样在用英文名作为工作表名是没问题的,但如果sheetName是中文字符,就会出现乱码,解决的方法如下代码:

  
     HSSFSheet  sheet= workbook.createSheet();

     workbook.setSheetName(0, sheetName,(short)1); //这里(short)1是解决中文乱码的关键;而第一个参数是工作表的索引号。

猜你喜欢

转载自www.cnblogs.com/konglxblog/p/10012142.html