2012-12-13 27 views
0

我有一些Java代碼讀取Excel數據。在運行Java代碼時,它顯示以下錯誤。幫助我解決這個問題。另外,我需要知道其他讀取.xlsx文件的方法。問題而閱讀Excel文件(Java代碼)

(小編輯)我怎麼能打印出他們各自的列行。例如:

Age 
19 
20 
21 

Salary 
35k 
20k 
40k 
. 
. 
. 

Exception in thread "main" org.apache.poi.poifs.filesystem.OfficeXmlFileException: The supplied data appears to be in the Office 2007+ XML. You are calling the part of POI that deals with OLE2 Office Documents. You need to call a different part of POI to process this data (eg XSSF instead of HSSF) at org.apache.poi.poifs.storage.HeaderBlock.(HeaderBlock.java:131) at org.apache.poi.poifs.storage.HeaderBlock.(HeaderBlock.java:104) at org.apache.poi.poifs.filesystem.POIFSFileSystem.(POIFSFileSystem.java:138) at org.apache.poi.hssf.usermodel.HSSFWorkbook.(HSSFWorkbook.java:322) at org.apache.poi.hssf.usermodel.HSSFWorkbook.(HSSFWorkbook.java:303) at ExcelRead.main(ExcelRead.java:18)

的Java代碼如下:

import java.io.File; 
import java.io.FileInputStream; 
import java.io.FileNotFoundException; 
import java.io.IOException; 
import java.util.Iterator; 

import org.apache.poi.hssf.usermodel.HSSFSheet; 
import org.apache.poi.hssf.usermodel.HSSFWorkbook; 
import org.apache.poi.ss.usermodel.Cell; 
import org.apache.poi.ss.usermodel.Row; 


public class ExcelRead { 
    public static void main(String[] args) { 

    try { 
     FileInputStream file = new FileInputStream(new File("C:/Users/vinayakp/Desktop/Book.xlsx")); 
     HSSFWorkbook workbook = new HSSFWorkbook(file); 
     HSSFSheet sheet = workbook.getSheetAt(0); 
     Iterator<Row> rowIterator = sheet.iterator(); 
     while(rowIterator.hasNext()) { 
      Row row = rowIterator.next(); 
      Iterator<Cell> cellIterator = row.cellIterator(); 
      while(cellIterator.hasNext()) { 
       Cell cell = cellIterator.next(); 
       switch(cell.getCellType()) { 
        case Cell.CELL_TYPE_BOOLEAN: 
         System.out.print(cell.getBooleanCellValue() + "\t\t"); 
         break; 
        case Cell.CELL_TYPE_NUMERIC: 
         System.out.print(cell.getNumericCellValue() + "\t\t"); 
         break; 
        case Cell.CELL_TYPE_STRING: 
         System.out.print(cell.getStringCellValue() + "\t\t"); 
         break; 
       } 
      } 
      System.out.println(""); 
     } 
     file.close();  
    } catch (FileNotFoundException e) { 
     e.printStackTrace(); 
    } catch (IOException ae) { 
     ae.printStackTrace(); 
    } 
} 
} 

回答

1

您使用了錯誤的類文件進行讀取HSSFWorkbook是老Excel格式。使用XSSFWorkbook代替

編輯:從http://www.coderanch.com/t/463779/java/java/read-xlsx-sheet-Client-Side複製 。 你做同樣的事情嗎?

try { 
System.out.println("destDir==> "+destDir); 
XSSFWorkbook workBook = new XSSFWorkbook(destDir); 
XSSFSheet sheet = workBook.getSheetAt(0); 
totalRows = sheet.getPhysicalNumberOfRows(); 
System.out.println("total no of rows >>>>"+totalRows); 

} catch (IOException e) { 
e.printStackTrace(); 
} 

編輯2: 瞭解從這個link

+0

我試圖與然而它給我同樣的錯誤。 –

+0

刪除導入HSSFWorkbook,然後導入XSSFWorkbook –

+0

@MohammodHossain後,我得到了下面的錯誤_Exception在線程「主」java.lang.NoClassDefFoundError:org/apache/xmlbeans/XmlObject \t在ExcelRead.main(ExcelRead.java:20) _ –

3

的Apache POI刪除previus導入類後,再加入

import org.apache.poi.ss.usermodel.Cell; 
import org.apache.poi.ss.usermodel.Row; 
import org.apache.poi.ss.usermodel.Sheet; 
import org.apache.poi.ss.usermodel.Workbook; 
import org.apache.poi.ss.usermodel.WorkbookFactory; 


private static void read(String path){ 
    Workbook workbook = null; 
    FileInputStream fis = null;   
    try { 
     File source = new File(path); 
     if(source.exists()){ 
     fis = new FileInputStream(source); 
     workbook = WorkbookFactory.create(source); 

     }else{ 
       JOptionPane.showMessageDialog(null, "File path is not exist.", "Error", JOptionPane.ERROR_MESSAGE); 
     }  

     Sheet sheet = null;   
     int lastRowNum = 0; 
     int numSheets = workbook.getNumberOfSheets();   
     for(int i = 0; i < numSheets; i++) {    
      sheet = workbook.getSheetAt(i); 
      if(sheet.getPhysicalNumberOfRows() > 0) {      
       lastRowNum = sheet.getLastRowNum();     
       int lastCellNum = 0;    
       for(Row row : sheet) {     
        Employee emp = new Employee();   

        int numOfCell = row.getPhysicalNumberOfCells(); 
        System.out.println("numOfCell:: "+numOfCell); 
        String stringValues [] = new String[numOfCell]; 
        for(Cell cell : row) { 
         // cell = row.getCell(cellIndex);       
         int cellIndex = cell.getColumnIndex();      
         logger.info("cellIndex:: "+ cellIndex); 
         switch (cell.getCellType()) { 

         case Cell.CELL_TYPE_FORMULA: 
          // printValue = "FORMULA value=" + cell.getCellFormula(); 
          stringValues[cellIndex] = cell.getCellFormula(); 
          break; 

         case Cell.CELL_TYPE_NUMERIC: 
          //printValue = "NUMERIC value=" + cell.getNumericCellValue(); 
          System.out.println("Value is numeric:: "+ cell.getNumericCellValue()); 
          stringValues[cellIndex] = String.valueOf(cell.getNumericCellValue()); 
          break; 

         case Cell.CELL_TYPE_STRING: 
          // printValue = "STRING value=" + cell.getStringCellValue(); 
          stringValues[cellIndex] = cell.getStringCellValue(); 
          break; 

         case Cell.CELL_TYPE_BLANK: 
          // printValue = "STRING value=" + cell.getStringCellValue(); 
          stringValues[cellIndex] = cell.getStringCellValue(); 
          break; 

         default: 
         } 


        }   

        } 


       } 
      }    
     }  

     } catch (InvalidFormatException e) { 
      logger.error(e.getMessage()); 
      e.printStackTrace(); 
     } catch (FileNotFoundException e) {   
      e.printStackTrace(); 
      logger.error(e.getMessage()); 
     } catch (IOException e) { 
      logger.error(e.getMessage()); 
      e.printStackTrace(); 
     } 
     catch (Exception e) { 
      logger.error(e.getMessage()); 
      e.printStackTrace(); 
     } 
     finally { 
      if (fis != null) { 
       try { 
        fis.close(); 
        fis = null; 
        } catch (IOException ioEx) { 
         logger.error(ioEx.getMessage()); 
       } 
      } 
     }  
    } 
+0

得到這個:_Exception在線程「主」java .lang.NoClassDefFoundError:組織/阿帕奇/ XMLBeans的你加入該庫在ExcelRead.main(ExcelRead.java:17)_ –

+0

/XmlObject中 \t? –

+2

在你的類路徑中添加xmlbeans-2.3.0.jar –

2

如果你想讀一個.xls文件時,必須使用HSSF (只支持.xls格式),但.xlsx文件,你必須使用XSSF或ANOT她的更高版本的API。

+1

耶知道這一事實。無論如何謝謝:)我得到了答案,代碼工作正常。 xml lib丟失 –

+0

哪個xml lib是這個Vinayak? – Reena