我编写了一个程序:12个数字可以从1到49中选择,结果组合编号会自动显示在电子表格中,因此每列中会有6个数字。
以下是我的代码。
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
答案 0 :(得分: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++;
}