我正在尝试从一个excel文件中的多个工作表中读取数据,在此过程中我遇到了一个问题或另一个问题。我现在遇到的当前问题是执行测试时遇到的“对象引用未设置为对象实例”。
我尝试使用OLEDB连接,但无济于事。我仍然是编码方面的新手,将不胜感激。
//的单例对象 公共类ExcelDataContext { //创建一个ExcelDataContext对象 私有静态只读ExcelDataContext实例=新的ExcelDataContext();
// no instantiated available
private static DataTable GetExcelDataContext(string filename)
{
FileStream stream = File.Open(filename, FileMode.Open, FileAccess.Read);
IExcelDataReader excelReader = ExcelReaderFactory.CreateOpenXmlReader(stream);
DataSet result = excelReader.AsDataSet(new ExcelDataSetConfiguration()
{
ConfigureDataTable = (_) => new ExcelDataTableConfiguration()
{
UseHeaderRow = true
}
});
foreach (DataTable sheet in result.Tables)
{
DataTableCollection tableCollection = result.Tables;
if (sheet.Equals(tableCollection["loginData"]))
{
DataTable loginDataTable = GetInstance().Sheets["loginData"];
return loginDataTable;
}
if (sheet.Equals(tableCollection["homeData"]))
{
DataTable homeDataTable = GetInstance().Sheets["homeData"];
return homeDataTable;
}
excelReader.Close();
}
return new DataTable();
}
// accessing to ExcelDataContext singleton
public static ExcelDataContext GetInstance()
{
return Instance;
}
// the dataset of Excel
public DataTableCollection Sheets => null;
public class DataCollection
{
public int RowNumber { get; set; }
public string ColName { get; set; }
public string ColValue { get; set; }
}
static readonly List<DataCollection> DataCollections = new List<DataCollection>();
public static void PopulateInCollection(string filename)
{
DataTable dataTable = GetExcelDataContext(filename);
for (int row = 1; row <= dataTable.Rows.Count; row++) //row =1 because we are not using header name
{
for (int col = 0; col < dataTable.Columns.Count; col++)
{
DataCollection collection = new DataCollection()
{
RowNumber = row,
ColName = dataTable.Columns[col].ColumnName, //return column name
ColValue = dataTable.Rows[row - 1][col].ToString()
};
DataCollections.Add(collection);
}
}
}
public static string ReadData(int rowNumber, string columnName)
{
try
{
string data =
(from colData in DataCollections
where colData.ColName == columnName && colData.RowNumber == rowNumber
select colData.ColValue).SingleOrDefault();
return data;
}
catch (Exception)
{
return null;
}
}
}
我希望能够从每个Excel工作表中获取数据。
答案 0 :(得分:0)
问题是:没有实例化的对象。尝试找出哪个类不是通过调试实例化的。