I'm trying to take XLSX data and putting it into an DataGridView using the ExcelDataReader NuGet package. But i get a Object reference not set to an instance of an object error on line 35
foreach (DataTable dt in result.Tables)
Here is the full code.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.OleDb;
using System.IO;
using Excel;
namespace MyForm
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
DataSet result;
private void butOpen_Click(object sender, EventArgs e)
{
using (OpenFileDialog ofd = new OpenFileDialog())
{
if (ofd.ShowDialog() == DialogResult.OK)
{
FileStream fs = File.Open(ofd.FileName, FileMode.Open, FileAccess.Read);
IExcelDataReader reader = ExcelReaderFactory.CreateBinaryReader(fs);
reader.IsFirstRowAsColumnNames = true;
result = reader.AsDataSet();
cboSheet.Items.Clear();
foreach (DataTable dt in result.Tables)
cboSheet.Items.Add(dt.TableName);
reader.Close();
}
}
}
private void cboSheet_SelectedIndexChanged(object sender, EventArgs e)
{
dataGridView.DataSource = result.Tables[cboSheet.SelectedIndex];
}
}
}
Here is the error message: Error
reader.AsDataSet()returns null and you're trying to access the propertyresult.Tables. Do you have an example of a .xlsx file to test this with?resultis taking null content. Try to debug and see what is the content ofresult. Also try to instantiate asDataSet result = new DataSet()ExcelDataREader.DataSet(now required to use theAsDataSet()extension method) i was able to read a xlsx file and access the tables in the dataset.