2016-08-11 24 views
1

我有一個excel工作表,在200列中的數據讀出excel表,要導入到DB以下代碼列不按順序讀出,同時用java

private File upp; 
InputStream input = new FileInputStream(upp); 
POIFSFileSystem fs = new POIFSFileSystem(input); 
HSSFWorkbook wb = new HSSFWorkbook(fs); 
HSSFSheet sheet = wb.getSheetAt(0); 

Iterator rows = sheet.rowIterator(); 

while(rows.hasNext()) { 
    String data=""; 
    HSSFRow row = (HSSFRow) rows.next(); 
    if(row.getRowNum() == 0 || row.getRowNum() == 1) { 
     Iterator rowCells = row.cellIterator(); 
     while(rowCells.hasNext()) { 
      HSSFCell cell = (HSSFCell) rowCells.next(); 
      for(int i=0; i <= cell.getCellNum(); i++) { 

      }    
      data = data + cell.getCellNum() + " ,"; 
     } 
     System.out.println(data); 
    } 
    slrow++; 
} 

即時除外我使用 輸出是

0 ,1 ,2 ,3 ,4 ,5 ,6 ,7 ,8 ,9 ,10 ,11 ,12 ,13 ,14 ,15 ,16 ,17 ,18 ,

但輸出是

0 ,1 ,2 ,3 ,4 ,5 ,6 ,7 ,8 ,9 ,10 ,11 ,12 ,13 ,14 ,15 ,17 ,16 ,18 ,

其以連續的順序不讀爲e xpected我無法找出其中的錯誤是在此代碼

+0

你能發佈給你這個問題的行的前20列嗎? –

+0

另外,最內層循環的真實版本是否會執行任何操作來丟失單元格,比如填充它們?因爲這可能解釋發生了什麼。 –

+0

'HSSFCell.getCellNum()'由於很長時間不推薦使用。使用'getColumnIndex()'。 –

回答

-1

使用JXL庫

<dependency> 
    <groupId>net.sourceforge.jexcelapi</groupId> 
    <artifactId>jxl</artifactId> 
    <version>2.6</version> 
</dependency 

代碼示例

FileInputStream inputStream = new FileInputStream(file); 
      Workbook wb = Workbook.getWorkbook(inputStream); 

      // TO get the access to the sheet. 
//For single sheet 
      Sheet sheet = wb.getSheet(0); 

      // To get the number of rows present in sheet 
      int totalNoOfRows = sheet.getRows(); 

      // To get the number of columns present in sheet 
      int totalNoOfCols = sheet.getColumns(); 

      Map<String, String> map = new HashMap<>(); 
      for (int row = 1; row < totalNoOfRows; row++) { 

       for (int col = 0; col < totalNoOfCols; col++) { 
        map.put(sheet.getCell(col, 0).getContents(), 
          sheet.getCell(col, row).getContents()); 

       } 
      } 

我希望這將是有益的。

+0

你怎麼知道這會有所幫助?有沒有保證這個庫不會因爲寫入文件而在同一個地方出現問題? –

+0

我已經使用過很多次了。它工作正常。 –

相關問題