当前位置: 首页 > 知识库问答 >
问题:

Apache poi方法将数据写入现有工作簿

纪翰
2023-03-14

这是我读写现有excel文件的课程。我一直在主类中通过传递filePath和fileName来调用这些函数。

   public class NewExcelFile {

    Workbook workbook;

    /******* Methods *******/
    // returns a workbook on giving the excel file's path and name
    public Workbook readExcel(String filePath, String fileName) {
        // Create object of File class to open xlsx file
        File file = new File(filePath + "\\" + fileName);
        // Create an object of FileInputStream class to read excel file
        FileInputStream inputStream = null;
        try {
            inputStream = new FileInputStream(file);
        } catch (FileNotFoundException e) {
            System.out.println("Error: Unable to find " + fileName + " in "
                    + filePath);
            e.printStackTrace();
        }
        Workbook workbook = null;
        // Find the file extension by spliting file name in substring and
        // getting only extension name
        String fileExtensionName = fileName.substring(fileName.indexOf("."));
        // Check condition if the file is xlsx file
        if (fileExtensionName.equals(".xlsx")) {
            // If it is xlsx file then create object of XSSFWorkbook class
            try {
                workbook = new XSSFWorkbook(inputStream);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        // Check condition if the file is xls file
        else if (fileExtensionName.equals(".xls")) {
            // If it is xls file then create object of XSSFWorkbook class
            try {
                workbook = new HSSFWorkbook(inputStream);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        this.workbook = workbook;
        return workbook;

    }

    public void writeExcel(String filePath, String fileName, String sheetName,
            String dataToWrite, int rowno) {

        System.out.println("WriteExcel" + filePath + " " + fileName + " "
                + sheetName + " " + dataToWrite + " " + rowno);

        Workbook newWorkbook = readExcel(filePath, fileName);
        Sheet sheet = newWorkbook.getSheet(sheetName);
        System.out.println("Sheet: " + sheet.getSheetName());

        Cell resultcell;

        ******resultcell = sheet.getRow(rowno).createCell(8);
        resultcell.setCellType(Cell.CELL_TYPE_STRING);
        resultcell.setCellValue(dataToWrite);

        CellStyle style = workbook.createCellStyle();
        if (dataToWrite == "P") {
            style.setFillBackgroundColor(IndexedColors.GREEN.getIndex());
            style.setFillPattern(CellStyle.ALIGN_FILL);
            resultcell.setCellStyle(style);
        } else if (dataToWrite == "F") {
            style.setFillBackgroundColor(IndexedColors.RED.getIndex());
            style.setFillPattern(CellStyle.ALIGN_FILL);
            resultcell.setCellStyle(style);
        }
        // Create an object of FileOutputStream class to create write data in
        // excel file
        File file = new File(filePath + "\\" + fileName);
        FileOutputStream outputStream = null;
        try {
            outputStream = new FileOutputStream(file);
        } catch (FileNotFoundException e) {
            System.out.println("File not found");
            e.printStackTrace();
        }

        // write data in the excel file and close output stream
        try {
            workbook.write(outputStream);
            outputStream.close();
        } catch (IOException e) {
            System.out.println("Error in writing to file");
            e.printStackTrace();
        }

    }

当我在main中使用readExcel获取一个工作簿并调用这个函数时:

Row row = testScriptsSheet.getRow(24);

我得到了正确的行,并且能够调用此行上的所有函数。但是对于写Excel()中完全相同的工作表中的完全相同的行,我得到了一个空指针异常(上面代码中***前面的行)。getRow()在这里给我null。我在这里做错了什么?

此外,我应该将workbook作为数据成员并在需要时执行< code > mynewexcelfile . workbook ,还是将它作为从主类中的readExcel返回的变量?我还想知道现在发生了什么,因为我没有在readExcel函数的末尾关闭inputStream。无论我是否关闭inputStream,我都会得到相同的错误。

编辑 - 添加主函数

public class NewDriver {

public static void main(String[] args) {
    System.out.println("Starting the framework");
    // initialise the workbook
    NewExcelFile testExecution = new NewExcelFile();
    testExecution.readExcel(System.getProperty("user.dir") + "\\",
            "abc.xlsx");

    // initialise sheets of workbook
    Sheet testSuiteSheet = testExecution.workbook.getSheet("TestSuite");
    Sheet testScriptsSheet = testExecution.workbook.getSheet("TestCases");
    Row row = testScriptsSheet.getRow(24);//gives the correct row

    //calling writeExcel gives npe in that line


        }
    }
}

}

共有2个答案

汲时铭
2023-03-14

根据我的理解,这似乎是一个概念上的错误。在调用 WriteExcel() 方法之前,您在 main 方法中所做的所有更改都在缓冲区中,而不是写入硬盘中的 excel 工作表/工作簿中。但是在 WriteExcel() 方法中,您传递的不是保存在缓冲区中的工作表或工作簿,而是硬盘驱动器中物理存在的工作表或工作簿的地址。因此,您在 main 函数中所做的任何更改都不存在,因此显示空指针异常。

e、 g.我有一个工作簿,比如我的D驱动器,A0中的值为1。现在我通过编程将其设置为2,但不执行写入操作,并暂停执行。同时,我去我的D驱动器打开工作表,因为更新的值在缓冲区中,所以只有1而不是2,直到我对该工作簿执行了写入操作。

建议:与其传递工作簿的地址,不如直接传递在main方法中使用的工作簿。

更新:不是main方法,实际上是< code>readExcel(String filePath,String fileName)方法。

艾和通
2023-03-14

在文档中,getRow(int)方法:

返回从 0 开始的逻辑行(非物理行)。如果请求未定义的行,则会得到一个 null。也就是说,第 4 行代表工作表上的第五行。

因此,当未定义行时,您必须首先创建行,然后创建单元格。

 类似资料:
  • 我正在处理一个项目,该项目需要读取Excel工作簿,调用必要的Web服务,然后从Web服务获取响应,并将该信息输入到已读取的同一Excel工作簿中。 以下是我在尝试写入Excel工作簿时看到的错误: 以下是我打开文件/读取的代码: 在此之后,我读取每一行并提取每个单元格值。 完成后,我将在成功和结果消息的标题下创建单元格,然后执行以下操作: 有人遇到过类似的问题吗?

  • 问题内容: 我正在一个项目中,该项目需要读取Excel工作簿,调用必要的Web服务,然后从Web服务获取响应,并将该信息输入到已读取的同一Excel工作簿中。 这是我尝试写入Excel工作簿时遇到的错误: 这是我打开文件/读取的代码: 之后,我读取每一行并提取每个单元格值。 完成此操作后,我将在“成功和结果消息”标题下创建单元格,然后执行以下操作: 有没有人遇到过类似的问题? 问题答案: 列出的当

  • 我需要检查工作表是否存在。如果存在,您必须键入下一个现有行,并且不要创建新的工作表。 您当前正在删除当前的电子表格,而我在电子表格中只写了一行。 我该如何解决这个问题?

  • 本文向大家介绍Python实现将数据框数据写入mongodb及mysql数据库的方法,包括了Python实现将数据框数据写入mongodb及mysql数据库的方法的使用技巧和注意事项,需要的朋友参考一下 本文实例讲述了Python实现将数据框数据写入mongodb及mysql数据库的方法。分享给大家供大家参考,具体如下: 主要内容: 1、数据框数据写入mongdb方法 2、数据框数据写入mysql

  • 我正在使用谷歌工作表来保存共享项目的数据。我使用Google的Sheets API访问数据,用python处理数据,并尝试在function writer中使用batchUpdate更新Sheets文件。 如果我将此函数数据作为列表传递,它将按预期工作 GoogleapClient。错误。HttpError: 任何指点都将不胜感激。

  • 本文向大家介绍Python实现读写sqlite3数据库并将统计数据写入Excel的方法示例,包括了Python实现读写sqlite3数据库并将统计数据写入Excel的方法示例的使用技巧和注意事项,需要的朋友参考一下 本文实例讲述了Python实现读写sqlite3数据库并将统计数据写入Excel的方法。分享给大家供大家参考,具体如下: 数据库初始化方法: 更多关于Python相关内容感兴趣的读者可