当我使用下面的方法时,这将打印excelsheet中的arraylist。当我在循环中调用此方法时,第二次迭代打印在同一工作表中。我想在不同的工作表中打印下一个迭代,可能创建一个新工作表并在那里写。我必须做出哪些更改才能在同一个excel工作簿的不同工作表中打印迭代。
for (int indexSelect=1;indexSelect>=10; indexSelect++){
excelWrite(Prints, indexSelect)
}
public static void excelWrite(ArrayList<Object> Prints, int indexSelect) {
XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet sheet = workbook.createSheet("Achievers"+indexSelect);
System.out.println("Getting sheet at ..:" +indexSelect);
//Sheet sheet = workbook.getSheetAt(indexSelect);
int rowCount = 0;
// for (Object Names : Prints) {
// org.apache.poi.ss.usermodel.Row row = sheet.createRow(++rowCount);
//org.apache.poi.ss.usermodel.Row row = sheet.createRow(rowCount);
int columnCount = indexSelect;
for (Object field :Prints) {
org.apache.poi.ss.usermodel.Row row = sheet.createRow(++rowCount);
Cell cell = row.createCell(columnCount);
if (field instanceof String) {
cell.setCellValue((String) field);
} else if (field instanceof Integer) {
cell.setCellValue((Integer) field);
}
}
// }
System.out.println("Current indexSelect is: "+indexSelect);
try {
FileOutputStream outputStream = new FileOutputStream("C:\\Softwares\\DataSource\\AchieversDataCopy.xlsx") ;
workbook.write(outputStream);
workbook.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
答案 0 :(得分:0)
只需从ExcelWrite方法中创建和保存工作簿:
XSSFWorkbook workbook = new XSSFWorkbook();
for (int indexSelect=1;indexSelect>=10; indexSelect++){
excelWrite(workbook, Prints, indexSelect)
}
try {
FileOutputStream outputStream = new FileOutputStream("C:\\Softwares\\DataSource\\AchieversDataCopy.xlsx") ;
workbook.write(outputStream);
workbook.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
public static void excelWrite(XSSFWorkbook workbook, ArrayList<Object> Prints, int indexSelect) {
XSSFSheet sheet = workbook.createSheet("Achievers"+indexSelect);
System.out.println("Getting sheet at ..:" +indexSelect);
int rowCount = 0;
int columnCount = indexSelect;
for (Object field :Prints) {
Row row = sheet.createRow(++rowCount);
Cell cell = row.createCell(columnCount);
if (field instanceof String) {
cell.setCellValue((String) field);
} else if (field instanceof Integer) {
cell.setCellValue((Integer) field);
}
}
System.out.println("Current indexSelect is: "+indexSelect);
}