2012-08-14 66 views
0

我已經寫了一個程序,12個數字可以從1到49中選擇,並且所得到的組合數字自動顯示在電子表格中,因此每列中會有6個數字。錯誤地顯示xls的內容

以下是我的代碼。

import java.io.FileOutputStream; 
import java.io.IOException; 
import org.apache.poi.ss.usermodel.CreationHelper; 
import org.apache.poi.xssf.usermodel.XSSFRow; 
import org.apache.poi.xssf.usermodel.XSSFSheet; 
import org.apache.poi.xssf.usermodel.XSSFWorkbook; 


public class Lotto { 

    /** 
    * @param args 
    * @throws IOException 
    */ 
    public static void main(String[] args) throws IOException { 
     int lotto[ ] = new int [12]; 
      boolean drawn; 
      for (int i=0; i<12; i++) { 
        do { 
          drawn = false; 
          lotto[i] = (int)(49*Math.random())+ 1; 
          for (int j=0; j<i; j++) 
            if (lotto[i] == lotto[j]) 
              drawn = true; 
        } while (drawn); 
      } 

      for(int i=0;i<12;i++){ 
       System.out.println(lotto[i]); 
      } 
      XSSFWorkbook wb = new XSSFWorkbook(); 
      FileOutputStream fileOut = new FileOutputStream("D:/workbook.xlsx"); 
      CreationHelper createHelper = wb.getCreationHelper(); 
      XSSFSheet sheet = wb.createSheet("new sheet"); 
      int i=0; 
      while(i<lotto.length/6){ 
       XSSFRow row = sheet.createRow(i); 
      for(int k=0;k<6;k++){ 
       for(int j=0;j<lotto.length;j++){ 

      row.createCell(k).setCellValue(lotto[j]); 
       } 
      } 
      i++; 
    } 
      // FileOutputStream fileOut = new FileOutputStream("workbook.xls"); 
      wb.write(fileOut); 
      fileOut.close(); 

    } 

} 

例如上述程序生成的隨機數如下所示。

30 44 39 7 6 33 19 28 31 21 49 22 

但xls文件被插入的

30 30 30 30 30 30 
44 44 44 44 44 44 

我需要輸出

30 44 39 7 6 33 
19 28 31 21 49 22 

請任何人都可以在此幫助。

+1

我決定不再看非格式化的代碼。我認爲我不是唯一的一個。如果您可以在發佈代碼之前對代碼進行格式化,那將非常有幫助。謝謝! – brimborium 2012-08-14 09:16:22

回答

2

編輯:新代碼,比較遺憾的是以前的錯誤...

我認爲這可能是一個邏輯的問題...試試這個:

XSSFRow row = null; 
int rowCounter = 0; 
int cellCounter = 0; 
for (int i = 0; i < lotto.length; i++) { 
    if ((i % 6) == 0) { 
     cellCounter = 0; 
     row = (XSSFRow) sheet.createRow(rowCounter); 
     rowCounter++; 
    } 
    row.createCell(cellCounter).setCellValue(lotto[i]); 
    cellCounter++; 
} 

希望它能幫助,

+1

-1你確定這會有幫助嗎?我可以看到由於樂透[i * 6 + j]導致的IndexBoundOutOFException – developer 2012-08-14 08:25:21

+0

它是否與編輯一起工作? – ArtiBucco 2012-08-14 10:56:44

+0

給我幾個小時請,我會讓你知道 – developer 2012-08-14 11:36:58