Hi jayjiaaa-5948,
Since you cannot separate the tables in the file separately, I suggest you can import specific columns and rows of Excel data into the datagridview.
Here is my test code example you can refer to.
private void Form1_Load(object sender, EventArgs e)
{
FileSelect();
}
public void FileSelect()
{
string filePath = string.Empty;
string fileExt = string.Empty;
OpenFileDialog file = new OpenFileDialog(); //open dialog to choose file
file.Filter = "Discovery Excel|*.xlsx| CSV (Coming Soon)| *.csv";
file.Title = "Please select a valid data file";
if (file.ShowDialog() == System.Windows.Forms.DialogResult.OK) //if there is a file choosen by the user
{
filePath = file.FileName; //get the path of the file
fileExt = Path.GetExtension(filePath); //get the file extension
if (fileExt.CompareTo(".xls") == 0 || fileExt.CompareTo(".xlsx") == 0)
{
try
{
DataTable dtExcel = new DataTable();
dtExcel = ReadExcel(filePath); //read file
dataGridView1.DataSource = dtExcel;
dataGridView1.AutoResizeColumns();
for (int i = 1; i < dataGridView1.RowCount - 1; i++)
{
if (dataGridView1.Rows[i].Cells[0].Value.ToString() == "" || dataGridView1.Rows[i].Cells[1].Value.ToString() == "")
{
dataGridView1.Rows.RemoveAt(i);
i--;
}
}
}
catch (Exception ex)
{
MessageBox.Show(" Something went wrong!");
}
}
else
{
MessageBox.Show("Please choose .xlsx or .CSV file only.", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Error); //custom messageBox to show error
}
}
}
public DataTable ReadExcel(string fileName)
{
var excel = new Microsoft.Office.Interop.Excel.Application();
var wkb = excel.Workbooks.Open(fileName, Type.Missing, Type.Missing, Type.Missing, Type.Missing,
Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing,
Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
var sheet = wkb.Sheets["Sheet1"] as Microsoft.Office.Interop.Excel.Worksheet;
//Select the data range of the exported table in excel
var range = sheet.Range[sheet.Cells[6, 2], sheet.Cells[10, 4]];
var data = range.Value2;
var dt = new DataTable();
dt.Columns.Add("ID");
dt.Columns.Add("Name");
dt.Columns.Add("Amount");
for (int i = 1; i <= range.Rows.Count; i++)
{
dt.Rows.Add(data[i, 1], data[i, 2], data[i, 3]);
}
return dt;
}
The result:
Here is also a code example by using OLEDB you can refer to.
Best Regards,
Daniel Zhang
If the response is helpful, please click "Accept Answer" and upvote it.
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.