1. 程式人生 > >poi匯出Excel Java POI匯入匯出Excel

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是解決中文亂碼的關鍵;而第一個引數是工作表的索引號。