2012-08-14 71 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