如何在Excel文件中添加新行?

huangapple go评论83阅读模式
英文:

How to add new row in Excel file?

问题

我在向 Excel 文件中添加新行方面遇到了问题。我的代码:

public static void setExcelFile(String Path, String SheetName) throws Exception {
    try {
        FileInputStream ExcelFile = new FileInputStream(Path);
        workBook = new XSSFWorkbook(ExcelFile);
        workSheet = workBook.getSheet(SheetName);
    } catch (Exception e) {
        throw (e);
    }
}

public static void setCellData(String path, String value, int RowNum, int ColNum) throws Exception {
    try {
        row = workSheet.getRow(RowNum);
        cell = row.getCell(ColNum);
        if (cell == null) {
            cell = row.createCell(ColNum);
            cell.setCellValue(value);
        } else {
            cell.setCellValue(value);
        }
        FileOutputStream fileOut = new FileOutputStream(path);
        workBook.write(fileOut);
        fileOut.flush();
        fileOut.close();
    } catch (Exception e) {
        throw (e);
    }
}

还有:

public static void main(String[] args) {
    String exPath = "C:\\Drivers\\excel\\test.xlsx";
    try {
        ExcelUtility.setExcelFile(exPath, "MainTable");
        ExcelUtility.setCellData(exPath, "Pizza", 4, 0);
        ExcelUtility.setCellData(exPath, "Thin", 4, 1);
        ExcelUtility.setCellData(exPath, "Peperoni", 4, 2);
        ExcelUtility.setCellData(exPath, "Katy", 4, 3);
        ExcelUtility.setCellData(exPath, "N/A", 4, 4);
        ExcelUtility.setCellData(exPath, "14.99", 4, 5);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

在我的 Excel 文件中,我有 4 行。使用上述代码,当我尝试更新任何现有行时,它运行得很好。但是当我尝试添加新行时,它会给我一个异常:

java.lang.NullPointerException
    at ui_automation.utils.ExcelUtility.setCellData(ExcelUtility.java:65)
    at ui_automation.stepDefinition.ExcelTest.main(ExcelTest.java:18)

有什么想法我做错了吗?

英文:

I have a problem with adding a new row in the excel file. My code:

public static void setExcelFile(String Path, String SheetName) throws Exception {
        try {
            FileInputStream ExcelFile = new FileInputStream(Path);
            workBook = new XSSFWorkbook(ExcelFile);
            workSheet = workBook.getSheet(SheetName);
        } catch (Exception e) {

            throw (e);

        }
    }    

public static void setCellData(String path, String value,  int RowNum, int ColNum) throws Exception {
        try{
            row  = workSheet.getRow(RowNum);
            cell = row.getCell(ColNum);
            if (cell == null) {
                cell = row.createCell(ColNum);
                cell.setCellValue(value);
            } else {
                cell.setCellValue(value);
            }
            FileOutputStream fileOut = new FileOutputStream(path);
            workBook.write(fileOut);
            fileOut.flush();
            fileOut.close();
        }catch(Exception e){

            throw (e);

        }

And:

public static void main(String[] args) {
        String exPath = "C:\\Drivers\\excel\\test.xlsx";
        try {
            ExcelUtility.setExcelFile(exPath, "MainTable");
            ExcelUtility.setCellData(exPath, "Pizza", 4, 0);
            ExcelUtility.setCellData(exPath, "Thin", 4, 1);
            ExcelUtility.setCellData(exPath, "Peperoni", 4, 2);
            ExcelUtility.setCellData(exPath, "Katy", 4, 3);
            ExcelUtility.setCellData(exPath, "N/A", 4, 4);
            ExcelUtility.setCellData(exPath, "14.99", 4, 5);
        } catch (Exception e) {
            e.printStackTrace();
        }


    }

In my excel file I have 4 row. With the above code when I tried to update any existing row it works great. But when I tried to add new row it give me exeption:

java.lang.NullPointerException
    at ui_automation.utils.ExcelUtility.setCellData(ExcelUtility.java:65)
    at ui_automation.stepDefinition.ExcelTest.main(ExcelTest.java:18)

Any ideas what I'm doing wrong?

答案1

得分: 2

空指针异常发生在您自己的代码中。您没有提供完整的源代码,也没有提供Excel文件(或者从开始时描述它有多少行和列),所以我无法确定具体是什么为空。但您可以查看ExcelUtility.java的第65行代码。

但仅仅从javadoc中观察,有一些可能性。首先,workSheet对象可能为空,因为**workBook.getSheet(SheetName)**如果没有名为“MainTable”的工作表,则返回null。另外,workSheet.getRow(RowNum)如果没有这样的行,仍然可能返回null值。请记住,行是从零开始计数的,所以当您要求第“4”行时,实际上是在请求第5行。您的Excel文件在此工作表中是否有五行?

如果这不是问题,那么尝试使用您正在使用的IDE的调试器,在“setCellData”方法的第一行(即在第RowNum行上设置断点)上设置断点,然后使用调试器查看所有变量的实际值。找出导致空指针异常的对象,然后向后跟踪代码,找出为什么它为空。如果您无法使调试器正常工作,您可以在代码的不同位置添加一些简单的System.out.println("variable: " + variable),以便在代码运行时查看这些值。

如果所有这些都无法帮助您找到问题,请发布完整的源代码(包括导入语句),行号与您代码中的行号相对应。同时,将“MainTable”工作表打开的Excel文件的屏幕截图也会有所帮助。

英文:

The null pointer exception happens in your own code. You haven't provided the full source code, nor the excel file (or described how many rows and columns it has from the start), so I can't say what exactly it is that is null. But you can just look at your code at line 65 of ExcelUtility.java.

But just looking at the javadoc, there are a few candidates. For one, the workSheet object might be null, since workBook.getSheet(SheetName) returns null if there is no sheet named "MainTable". Otherwise, workSheet.getRow(RowNum) can still result in a null value, if there is no such row. And remember that the row is zero-based, so when you ask for row "4" it is actually the 5th row you are asking for. Does your excel file have five rows in this sheet?

If this is not the problem, then try to use the debugger of the IDE you are using, and put a breakpoint at the first line inside the method "setCellData" (ie, put a breakpoint on row = workSheet.getRow(RowNum);) then use the debugger to see the actual value of all the variables. Find the object that is causing the Null Pointer Exception, then trace the code backwards until you find why it is null. If you can't get your debugger to work, you can just add some simple System.out.println("variable: " + variable") at different places in your code, so that you can see the values when the code runs.

If nothing of this helps you find the problem, please post the full source code (including imports), with line numbers matching the one in your code. And a screenshot of your excel file, with the "MainTable" sheet open would help too.

huangapple
  • 本文由 发表于 2020年9月27日 01:52:01
  • 转载请务必保留本文链接:https://go.coder-hub.com/64080870.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定