写入数据在Java中第一个选项卡数据不会显示,而写第二个选项卡

当我将数据添加到Excel表格中的第二个选项卡。 第一个标签数据不显示。 如果我删除第二个选项卡的代码,第一个选项卡数据是可见的。

HSSFSheet sheet1 = wb.createSheet("A "); HSSFSheet sheet2 = wb.createSheet("B"); HSSFFont headerFont = wb.createFont(); headerFont.setBoldweight(Font.BOLDWEIGHT_BOLD); headerStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND); headerStyle.setFillForegroundColor(HSSFColor.PALE_BLUE.index); headerStyle.setFillBackgroundColor(HSSFColor.WHITE.index); headerStyle.setFont(headerFont); try { FileOutputStream fileOut = new FileOutputStream("C:\\Report.xls"); HSSFRow sessionname = sheet1.createRow(0); HSSFCell title = sessionname.createCell(0); title.setCellStyle(headerStyle); title.setCellValue("Supported cipher Report"); HSSFRow row = sheet1.createRow(5); HSSFCell cell0 = row.createCell(0); cell0.setCellStyle(headerStyle); cell0.setCellValue("One"); HSSFCell cell1 = row.createCell(1); cell1.setCellStyle(headerStyle); cell1.setCellValue("two"); HSSFCell cell2 = row.createCell(2); cell2.setCellStyle(headerStyle); cell2.setCellValue("three"); HSSFCell cell3 = row.createCell(3); cell3.setCellStyle(headerStyle); cell3.setCellValue("four"); HSSFCell cell4 = row.createCell(4); cell4.setCellStyle(headerStyle); cell4.setCellValue("five"); if (!list.isEmpty()) { int rowNumber = 6; for (Result s : supportedlist) { HSSFRow nextrow = sheet1.createRow(rowNumber); nextrow.createCell(0).setCellValue(s.One()); nextrow.createCell(1).setCellValue(s.Two()); nextrow.createCell(2).setCellValue(s.Three()); nextrow.createCell(3).setCellValue(s.four()); nextrow.createCell(4).setCellValue(s.five()); rowNumber++; } } sheet1.autoSizeColumn(0); sheet1.autoSizeColumn(1); sheet1.autoSizeColumn(2); sheet1.autoSizeColumn(3); sheet1.autoSizeColumn(4); System.out.println("sheet1 writting"); wb.write(fileOut); fileOut.flush(); fileOut.close(); 

当我通过sheet2和剩余的代码是一样的上面。 sheet2数据显示时不显示sheet1选项卡数据。

我认为你正在做的是在写入sheet1之后将sheet1的值更改为sheet2 。 现在,根据你的代码会发生什么,你是再次创build/写入文件。 因此,它将replaces旧的文件和数据,并写入第二张表中的新文件。

第二次运行程序时,下面的行将覆盖数据

  FileOutputStream fileOut = new FileOutputStream("C:\\Report.xls"); 

你应该做的是写入sheet2你应该检查文件是否存在。 如果存在,则会将新工作表添加到现有的Excel文件中。 如果不存在,则创build一个新文件,然后创build一个工作表。

做这样的事情

  FileOutputStream fileOut = new FileOutputStream(file); if (file.exists()) { try { workbook = (HSSFWorkbook)WorkbookFactory.create(file); } catch (InvalidFormatException e) { e.printStackTrace(); } HSSFSheet sheet = workbook.createSheet("Sample sheet2"); } else{ workbook = new HSSFWorkbook(); HSSFSheet sheet = workbook.createSheet("Sample sheet1"); } workbook.write(fileOut); fileOut.close(); 

为了避免覆盖到下面的现有文件使用。 这将把数据追加到现有的文件。

 FileOutputStream fileOut = new FileOutputStream("C:\\Report.xls", true); 

问题是我创build了两个实例[new createExcel(one); 和新的createExcel(两个); 同时调用该函数。 因为wb是实例的一部分。 所以它创build了与Sheet1和Sheet2里面的新的Excel。 而这一次我只写了sheet2数据。 所以sheet2数据只显示。 感谢您的支持。