这是我的代码:
public static String[] array1 = {"devu","xyz","test","bb","run"};
public static String[] array2 = {"dvu","yz","tet","b","run"};
String excelFileName = "C:/Users/admin/IdeaProjects/Google_Demo/Write1.xlsx";//name of excel file
String sheetName = "Sheet1";//name of sheet
XSSFWorkbook wb = new XSSFWorkbook();
XSSFSheet sheet = wb.createSheet(sheetName);
//iterating r number of rows
for (int r = 0; r < 5; r++) {
XSSFRow row = sheet.createRow(r);
//iterating c number of columns
for (int c = 0; c < 1; c++) {
if (!row.equals(null)) {
XSSFCell cell = row.createCell(c);
cell.setCellValue(array1[r]);
}
}}
int count1 = 0;
for (int r = 0; r < 5; r++) {
XSSFRow row1 = sheet.createRow(r);
//iterating c number of columns
for (int c = 2; c < 3; c++) {
if (row1.equals(null)) {
row1 = sheet.createRow(count1);
}
XSSFCell cell = row1.createCell(c);
cell.setCellValue(array2[r]);
count1++;
}
}
FileOutputStream fileOut1 = new FileOutputStream(excelFileName);
//write this workbook to an Outputstream.
wb.write(fileOut1);
//fileOut.flush();
fileOut1.close();
}
我已经使用Selenium webdriver和POI采集了2个数组并写入数据到excel。
如果我只写第一个数组的数据,但是第二个数组的循环运行,它会从excel的第一列中删除数据,而只将第二个数组的数据写到新列中,因此效果很好。
最佳答案
这是因为您再次在第二个row
中创建了一个新的for loop
。下面的行应删除,以使您的代码按照规定的行为工作-
XSSFRow row1 = sheet.createRow(r);
以下是完整的更新代码-
public static String[] array1 = {"devu","xyz","test","bb","run"};
public static String[] array2 = {"dvu","yz","tet","b","run"};
String excelFileName = "C:/Users/admin/IdeaProjects/Google_Demo/Write1.xlsx";//name of excel file
String sheetName = "Sheet1";//name of sheet
XSSFWorkbook wb = new XSSFWorkbook();
XSSFSheet sheet = wb.createSheet(sheetName);
//iterating r number of rows
for (int r = 0; r < 5; r++) {
XSSFRow row = sheet.createRow(r);
//iterating c number of columns
for (int c = 0; c < 1; c++) {
XSSFCell cell = row.createCell(c);
cell.setCellValue(array1[r]);
}
}
for (int r = 0; r < 5; r++) {
XSSFRow row = sheet.getRow(r);
// As per current input and code, this if block will never execute.
// However, adding it so that later, if first for loop will change, this code can work.
if(row == null){
row = sheet.createRow(r);
}
//iterating c number of columns
for (int c = 2; c < 3; c++) {
XSSFCell cell = row1.createCell(c);
cell.setCellValue(array2[r]);
}
}
FileOutputStream fileOut1 = new FileOutputStream(excelFileName);
//write this workbook to an Outputstream.
wb.write(fileOut1);
//fileOut.flush();
fileOut1.close();