首页 > 解决方案 > 我想通过迭代行在 Excel 工作表中编写一组随机数。我可以编写随机数,但无法将它们存储在 excel 中

问题描述

我想生成随机数和并行我想将它们写在第一列的 excel 表中,最多 15 行。我尝试使用下面的脚本,但是它不起作用。

我尝试使用下面的脚本,每次我想存储多达 15 个数字并且这些数字不应该重复。

我尝试使用以下方法,但我不知道如何迭代它们。随机数和 Excel 单元格。

public long Random_Number() {
    Random rand = new Random();
    long drand = (long)(rand.nextDouble()*1000000000L);
    long correct = 0;
    String numberString = Long.toString(drand);

    if (numberString.length() == 8) {
         System.out.println(drand+ "It's not a 9 digit");
    }
    else if (numberString.length() == 9) {
        correct = drand;
        System.out.println(correct);              
    }

    return correct; 
}

public void writeData_Int_SSN( int cellNum) {
    try {
        File src = new File("filename.xls");
        Cell cell = null;
        FileInputStream fis = new FileInputStream(src);
        HSSFWorkbook wb = new HSSFWorkbook(fis);
        HSSFSheet sh1 = wb.getSheetAt(0);
        long gid = Random_Number();
        String GroupID = Long.toString(gid);
        System.out.println(GroupID);
        int num = Integer.parseInt(GroupID);

        for (int i = 1; i < 12; i++) {
            System.out.println("Entering into excel sheet");
            cell = sh1.getRow(i).getCell(cellNum);
            System.out.println("Iterating cells");

            if (cell.getCellType() == Cell.CELL_TYPE_STRING) {
                System.out.println("We are  entering  numeric data");
                int str1 = Integer.parseInt(cell.getStringCellValue());
                System.out.println(str1);
                cell.setCellValue(num);
            }
        }

        FileOutputStream fout = new FileOutputStream(new File("filename.xls"));
        wb.write(fout);
        fout.close();
    } 
    catch (Exception e) {
        System.out.println(e.getMessage());
    }
}

标签: apache-poiexcel-reader

解决方案


推荐阅读