我正在尝试将数据写入不同工作表中的同一个 excel 文件,下面是我在这里尝试的代码,只有一个工作表正在创建,并且该工作表中的数据正在更新,新工作表名称覆盖旧工作表。在这里,我用 2 个不同的工作表名称调用调用方法两次,当我们从第一次调用时,数据需要在 sheet1 中更新,而第二次调用数据需要在 sheet2 中更新,但在此代码中,只有 sheet2 正在创建和数据更新。
public static void call(Map<String, String[]> dataListLMS_IPS, String sheet)
{
try {
String filePath = "C:\\Users\\PATIV25\\Downloads\\APEX UPEX.xlsx";
File theDir = new File(filePath);
String filename = theDir.toString();
FileOutputStream fileOut = new FileOutputStream(filename);
fileOut.close();
XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet spreadsheet = workbook.createSheet(sheet);
XSSFRow row;
Set<String> keyid = dataListLMS_IPS.keySet();
int rowid = 0;
// writing the data into the sheets...
CellStyle style = workbook.createCellStyle();
style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
for (String key : keyid) {
row = spreadsheet.createRow(rowid++);
String[] i = dataListLMS_IPS.get(key);
int cellid = 0;
int a = 0;
for (String obj : i) {
Cell cell = row.createCell(cellid++);
cell.setCellValue(obj);
if (rowid != 1) {
if (i[2].equals(i[6]) && i[3].equals(i[7])) {
style.setFillForegroundColor(IndexedColors.BRIGHT_GREEN.getIndex());
cell.setCellValue(obj);
if (a == 2 || a == 3 || a == 6 || a == 7)
cell.setCellStyle(style);
a++;
}
}
}
}
// .xlsx is the format for Excel Sheets...
// writing the workbook into the file...
FileOutputStream out = new FileOutputStream(theDir);
workbook.write(out);
out.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
public static void main(String[] arg) throws Exception {
Map<String, String[]> data = new LinkedHashMap<>();
data.put("A", new String[]{"ACC NO: ", "REPORT TYPE", "PAYMENTID", "AMOUNT", "REPORT TYPE", "PAYMENTID", "AMOUNT", "RESULT"});
data.put("v", new String[]{"ACC NO: ", "REPORT TYPE", "PAYMENTID", "AMOUNT", "REPORT TYPE", "PAYMENTID", "AMOUNT", "RESULT"});
call(data, "sheet1");
call(data, "sheet2");
}