![](/img/trans.png)
[英]c#: Accessing cells in excel worksheet throws NullReferenceException
[英]NullReferenceException accessing Workbook Cells with NPOI
我正在使用Oracle.ManagedDataAccess。 我试图将所有值输出到XML中并且它有效。 但是,我现在遇到问题,现在使用NPOI库将这些值写入excel文件。
我编写了webservice,它从数据库获取数据并将其写入excel文件。
将数据库表中的值分配给Excel单元格时出错。
码:
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();
}
}
}
我收到此错误:
System.NullReferenceException:未将对象引用设置为对象的实例。
在这部分代码上:
wb.GetSheet("Report1").GetRow(i).GetCell(j).SetCellValue(dataReader.GetValue(j).ToString());
我认为你的while循环不正确。 它应该是这样的:
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件事:
我不熟悉NPOI.XSSF
库,可能不完全正确。 我用它作为参考 - https://www.tutorialspoint.com/apache_poi/apache_poi_cells.htm
再说一遍,因为我不知道NPOI.XSSF
,我不知道它在创建excel表时的价值。 但我可以告诉你,对于创建Excel工作表,我知道最简单的方法是使用microsoft.ace.oledb.xx
库。 它允许使用工作表,就像它是一个数据表一样。 您可以使用Dataset
从Oracle加载它,然后将它保存到Excel,这是一个简单的步骤。 或者您可以使用阅读器逐个进行,然后使用常规SQL语法“Insert Into ...”进入工作表。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.