2011-12-29 89 views
4

其實我正在從一個從Excel文件中提取數據的java程序, 和我正在使用POI庫,事實上,我必須指定每個提取的值的類型,但該文件包含大量的不同類型的數據, 所以我問是否有另一種方式來獲取所有的數據作爲一個字符串。如何從excel文件中獲取數據?

謝謝。 最好的問候

package DAO; 

import java.io.FileInputStream; 
import java.util.Iterator; 
import java.util.Vector; 

import org.apache.poi.hssf.usermodel.HSSFCell; 
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 ReadExcelFile { 

    public static void main(String[] args) { 
     String fileName = "C:\\Users\\marrah\\Desktop\\TRIAL FILE1.xls"; 
     Vector dataHolder = ReadCSV(fileName); 
     printCellData(dataHolder); 
    } 

    public static Vector ReadCSV(String fileName) { 
     Vector cellVectorHolder = new Vector(); 

     try { 
      FileInputStream myInput = new FileInputStream(fileName); 
      POIFSFileSystem myFileSystem = new POIFSFileSystem(myInput); 
      HSSFWorkbook myWorkBook = new HSSFWorkbook(myFileSystem); 
      HSSFSheet mySheet = myWorkBook.getSheetAt(0); 
      Iterator rowIter = mySheet.rowIterator(); 

      while (rowIter.hasNext()) { 
       HSSFRow myRow = (HSSFRow) rowIter.next(); 
       Iterator cellIter = myRow.cellIterator(); 
       Vector cellStoreVector = new Vector(); 
       while (cellIter.hasNext()) { 
        HSSFCell myCell = (HSSFCell) cellIter.next(); 
        cellStoreVector.addElement(myCell); 
       } 
       cellVectorHolder.addElement(cellStoreVector); 
      } 
     } catch (Exception e) { 
      e.printStackTrace(); 
     } 
     return cellVectorHolder; 
    } 

    private static void printCellData(Vector dataHolder) { 
     for (int i = 0; i < dataHolder.size(); i++) { 
      Vector cellStoreVector = (Vector) dataHolder.elementAt(i); 
      for (int j = 0; j < cellStoreVector.size(); j++) { 
       HSSFCell myCell = (HSSFCell) cellStoreVector.elementAt(j); 
       Object stringCellValue=""; 
       stringCellValue =cellStoreVector.get(j).toString(); 
       System.out.print(stringCellValue.toString()+"\t"); 
      } 
     } 
    } 
} 
+0

你想,他們在Excel中的樣子,或者你想控制施加給每個日期的格式來獲取值細胞,每個細胞等? – Gagravarr 2011-12-30 10:19:28

回答

1

您可以創建一個共同的功能,當你運行直通每一行,其驗證數據類型上的每一個細胞都使用,然後檢索它在你的首選格式。所以你移動行與行,並且對於每個單元調用是這樣的:

private static String getCellvalue(HSSFRow poiRow, int intColActual) { 

     if (poiFilaActual != null && poiRowActual.getLastCellNum() >= (short) intColActual) { 
      HSSFCell cell = poiRowActual.getCell(intColActual); 
      if (cell != null) { 
       if (HSSFCell.CELL_TYPE_STRING == cell.getCellType()) { 
        return cell.getRichStringCellValue().toString(); 
       } else if (HSSFCell.CELL_TYPE_BOOLEAN == cell.getCellType()) { 
        return new String((cell.getBooleanCellValue() == true ? "true" : "false")); 
       } else if (HSSFCell.CELL_TYPE_BLANK == cell.getCellType()) { 
        return ""; 
       } else if (HSSFCell.CELL_TYPE_NUMERIC == cell.getCellType()) { 
        if(HSSFDateUtil.isCellDateFormatted(cell)){ 
         return (new SimpleDateFormat("dd/MM/yyyy").format(cell.getDateCellValue())); 
        }else{ 
         return new BigDecimal(cell.getNumericCellValue()).toString(); 
        } 
       } 
      } 
     } 

     return null; 
    } 
2

我有一個單元測試,我使用以下方法來提取一個Excel文件中的所有文本沒有任何格式的,對於一些用例,這可能是比遍歷所有的元素一個接一個更快:

private POITextExtractor extractText(File file) throws IOException { 

    InputStream inp = null; 

    try { 

     inp = new PushbackInputStream(

      new FileInputStream(file), 8); 



     if(POIFSFileSystem.hasPOIFSHeader(inp)) { 

      return createExtractor(new POIFSFileSystem(inp)); 

     } 

     throw new IllegalArgumentException("Your File was neither an OLE2 file, nor an OOXML file"); 

    } finally { 

     if(inp != null) inp.close(); 

    } 

} 



private static POITextExtractor createExtractor(POIFSFileSystem fs) throws IOException { 

    return createExtractor(fs.getRoot(), fs); 

} 



private static POITextExtractor createExtractor(DirectoryNode poifsDir, POIFSFileSystem fs) throws IOException { 

    for(Iterator<Entry> entries = poifsDir.getEntries(); entries.hasNext();) { 

     Entry entry = entries.next(); 



     if(entry.getName().equals("Workbook")) { 

      { 

       return new ExcelExtractor(poifsDir, fs); 

      } 

     } 

    } 

    throw new IllegalArgumentException("No supported documents found in the OLE2 stream"); 

} 



private String assertContains(File file, String... contents) throws IOException { 

    assertTrue(file.exists()); 

    POITextExtractor extractor = extractText(file); 

    assertNotNull(extractor); 

    String str = extractor.getText(); 



    for(String s : contents) { 

     assertTrue("Did expect to find text '" + s + "' in resulting Excel file, but did not find it in str: " + str, str.contains(s)); 

    } 



    return str; 

}