2012-04-07 62 views
0

我設法將數據寫入單個列。 我的要求是將數據寫入下一個相鄰列,而不會覆蓋第一列中的數據。 有什麼幫助嗎?使用apache poi將數據導出到excel表欄明智嗎?

InputStream inp; 
    try { 
     inp = new FileInputStream("D:\\test.xls"); 
     Workbook wb = WorkbookFactory.create(inp); 
     Sheet sheet = wb.getSheetAt(0); 
     Row row = null; 

     Cell c = null; 

     int rowNum=0; 
     Set<String> keySet = new HashSet<String>(); 
     keySet = tushMap.keySet(); 
     for (Entry<String, String> entry : tushMap.entrySet()) { 
      row=sheet.createRow((short) (sheet.getLastRowNum() + 1)); 
      System.out.println((short) (sheet.getLastRowNum() + 1)); 
      c = row.createCell(0); 
      c.setCellValue("fff"); 
      System.out.println("fff"); 
      System.out.println(entry.getKey() + "/" + entry.getValue()); 
      rowNum++; 
     } 


     FileOutputStream fileOut = new FileOutputStream("D:\\test.xls"); 
     wb.write(fileOut); 
     fileOut.close(); 

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

這是寫入填充第1列的代碼。 填充第二列覆蓋拳頭1 .. PLS提出一些解決方案.. 預先感謝。

回答

1

要並排獲取數據,請獲取循環外的最後一行並將其保存爲循環行。在循環內保留一個計數器,用於編輯哪一行。如果該行爲空,則創建該行。

rowPos = sheet.getLastRowNum(); 
for (Entry<String, String> entry : tushMap.entrySet()) { 
    rowPos++; 
    Row currentRow = sheet.getRow(rowPos); 
    if(null == currentRow) 
     currentRow = createRow(rowPos); 

編輯:

我正在使用該

int beginingRow = sheet.getLastRowNum(); 
      for(int col=0; col<2; col++){ 
       int currentRow = beginingRow; 
       for (int i=0; i<10; i++) { 
        currentRow++; 
        row = sheet.getRow(currentRow); 
        if(null == row) 
         row=sheet.createRow(currentRow); 
        c = row.createCell(col); 
        c.setCellValue("fff"); 
        System.out.println("fff"); 
        //System.out.println(entry.getKey() + "/" + entry.getValue()); 
        rowNum++; 
       } 
      } 

輸出

fff fff 
fff fff 
fff fff 
fff fff 
fff fff 
fff fff 
fff fff 
fff fff 
fff fff 
fff fff 
+0

做過desierd輸出that..also改變sheet.getLastRowNum()+ 1到片.getFirstRowNum()+1(+1以跳過列標題) – 2012-04-07 08:20:15

+0

編輯是否有幫助? – 2012-04-07 08:31:33

+0

謝謝尼廷,幫助:) – 2012-04-07 11:42:57