简体   繁体   English

使用NPOI访问工作簿单元格的NullReferenceException

[英]NullReferenceException accessing Workbook Cells with NPOI

I am using Oracle.ManagedDataAccess. 我正在使用Oracle.ManagedDataAccess。 I tried to output all the values into XML and it worked. 我试图将所有值输出到XML中并且它有效。 However, I am having problem now writing those values into excel file using NPOI library. 但是,我现在遇到问题,现在使用NPOI库将这些值写入excel文件。

I wrote webservice that takes data from Database and writes it to excel file. 我编写了webservice,它从数据库获取数据并将其写入excel文件。

I get error when assigning value from Database table to Excel cell. 将数据库表中的值分配给Excel单元格时出错。

Code: 码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.IO;
using System.Data;
using System.Configuration;
using System.Configuration.Assemblies;
using Oracle.ManagedDataAccess;
using Oracle.ManagedDataAccess.Client;
using Oracle.ManagedDataAccess.Types;
using NPOI;
using NPOI.XSSF.UserModel;


namespace Example
{
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]

    public class WebService2 : System.Web.Services.WebService
    {

        [WebMethod]
        public string dictToExcel(string dict_name)
        {

            string connectionString = ConfigurationManager.ConnectionStrings["OracleConnection"].ConnectionString;
            OracleConnection connection = new OracleConnection(connectionString);

            connection.Open();

            OracleCommand cmd = new OracleCommand();
            cmd.Connection = connection;

            cmd.CommandText = "SELECT * from TB_EXAMPLE";
            cmd.CommandType = CommandType.Text;

            OracleDataReader dataReader = cmd.ExecuteReader();

            using (FileStream stream = new FileStream(@"filepath\new.xlsx", FileMode.Create, FileAccess.Write))
            {
                XSSFWorkbook wb;
                XSSFSheet sh;
                wb = new XSSFWorkbook();
                sh = (XSSFSheet)wb.CreateSheet("Report1");

                while (dataReader.Read())
                {
                    for (int i = 0; i < 2; i++)
                    {
                        var r = sh.CreateRow(i);
                        for (int j = 0; j < 2; j++)
                        {
                            wb.GetSheet("Report1").GetRow(i).GetCell(j).SetCellValue(dataReader.GetValue(j).ToString());
                        }
                    }
                    wb.Write(stream);
                }
            }           
            return "Done!";
            connection.Close();
        }
    }
}

I get this error: 我收到此错误:

System.NullReferenceException: Object reference not set to an instance of an object. System.NullReferenceException:未将对象引用设置为对象的实例。

on this part of code: 在这部分代码上:

wb.GetSheet("Report1").GetRow(i).GetCell(j).SetCellValue(dataReader.GetValue(j).ToString());

Your while loop is not correct, I think. 我认为你的while循环不正确。 It should be something like this: 它应该是这样的:

XSSFWorkbook wb = new XSSFWorkbook();
XSSFSheet sh = (XSSFSheet)wb.CreateSheet("Report1");
var rowIdex = 0;

while (dataReader.Read())
{
    var row = sh.CreateRow(rowIdex);
    for (int colIndex = 0; colIndex < dataReader.FieldCount; colIndex++)
    {
        row.CreateCell(colIndex).
            SetCellValue(dataReader[colIndex].ToString()); 
    }
    rowIdex++;
}

2 Things: 2件事:

  • I am not familiar with NPOI.XSSF library and may be not entirely correct. 我不熟悉NPOI.XSSF库,可能不完全正确。 I used this as reference - https://www.tutorialspoint.com/apache_poi/apache_poi_cells.htm 我用它作为参考 - https://www.tutorialspoint.com/apache_poi/apache_poi_cells.htm

  • Again, because I don't know about NPOI.XSSF , I don't know its value in creating excel sheet. 再说一遍,因为我不知道NPOI.XSSF ,我不知道它在创建excel表时的价值。 But I can tell you that for creating Excel sheets, the easiest way I know is to use microsoft.ace.oledb.xx library. 但我可以告诉你,对于创建Excel工作表,我知道最简单的方法是使用microsoft.ace.oledb.xx库。 It allows to work with sheet just as if it was a data table. 它允许使用工作表,就像它是一个数据表一样。 You could use Dataset load it from Oracle and then save it to Excel it couple easy steps. 您可以使用Dataset从Oracle加载它,然后将它保存到Excel,这是一个简单的步骤。 Or you could go one by one using reader and then using regular SQL syntax "Insert Into..." into your sheet. 或者您可以使用阅读器逐个进行,然后使用常规SQL语法“Insert Into ...”进入工作表。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM