I'm trying to display the Excel sheet on DataGrindView. I found a solution on internet but I'm getting an error when I tried to browse the Excel file. Would anyone help me on this topic?
Browse button codes are stated below:
private void btnBrowse_Click(object sender, EventArgs e)
{
using (OpenFileDialog openFileDialog = new OpenFileDialog() { Filter = "Excel 97-2003 Workbook|*.xls|Excel Workbook|*.xlsx" })
{
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
txtFilename.Text = openFileDialog.FileName;
using (var stream = File.Open(openFileDialog.FileName, FileMode.Open, FileAccess.Read))
{
using (IExcelDataReader reader = ExcelReaderFactory.CreateReader(stream))
{
DataSet result = reader.AsDataSet(new ExcelDataSetConfiguration()
{
ConfigureDataTable = (_) => new ExcelDataTableConfiguration() { UseHeaderRow = true }
});
tableCollection = result.Tables;
cboxSheet.Items.Clear();
foreach (DataTable table in tableCollection)
cboxSheet.Items.Add(table.TableName);//add sheet to combobox
}
}
}
}
}
EDIT:
Hello again,
This's my first time posting something on Stackoverflow so sorry for my mistakes.
I'm going to explain more detailed about the project and the error.
This's my Form Application format
And here's the Form code.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using ExcelDataReader;
using System.Data.OleDb;
namespace emailsender
{
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
private void Form2_Load(object sender, EventArgs e)
{
}
private void cboxSheet_SelectedIndexChanged(object sender, EventArgs e)
{
dataGridView1.DataMember = cboxSheet.SelectedItem.ToString();
}
private void btnBrowse_Click(object sender, EventArgs e)
{
using (OpenFileDialog openFileDialog = new OpenFileDialog() { Filter = "Excel 97-2003 Workbook|*.xls|Excel Workbook|*.xlsx" })
{
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
txtFilename.Text = openFileDialog.FileName;
using (var stream = File.Open(openFileDialog.FileName, FileMode.Open, FileAccess.Read))
{
using (IExcelDataReader reader = ExcelReaderFactory.CreateReader(stream))
{
DataSet result = reader.AsDataSet(new ExcelDataSetConfiguration()
{
ConfigureDataTable = (_) => new ExcelDataTableConfiguration() { UseHeaderRow = true }
});
//tableCollection = result.Tables;
cboxSheet.Items.Clear();
foreach (DataTable table in result.Tables)
cboxSheet.Items.Add(table.TableName);//add sheet to combobox
dataGridView1.DataSource = result;
cboxSheet.SelectedIndex = 0;
}
}
}
}
}
}
}
I tried @JohnG's sample but when I select the file with the file explorer and press the open button I get the same error.
I cannot quite grasp the point I missed...