I've tried numerous methods I've seen online to copy a Excel file to a DataGridView, but none worked. My main problem is that with those methods there's a problem about fully understanding how they work without a proper explanation or they just give me strange errors, like one that told me that the Excel sheet I wanted to copy was a null instance of an object. I want to specify that I can easily work on the Excel file with other functions and I get no errors at all, I also don't need any kind of manipulation on the Excel file for this, just a plain way to copy it. Btw I started using C# just 2 days ago for a stage-thing for school, that's why I don't know much.
Right-click on your project's name or References and select Manage NuGet Packages .
Under the Browse tab, search for free spire.xls and install it.
Use the code below to transfer data from Excel to DataGridView.
private void button1_Click(object sender, EventArgs e) { Workbook workbook = new Workbook(); workbook.LoadFromFile(@"C:\Users\Administrator\Desktop\Data.xlsx"); Worksheet worksheet = workbook.Worksheets[0]; //Export data in the worksheet to a DataTable DataTable dt = worksheet.ExportDataTable(); //This overload enables you to specify the range to be exported along with whether to export column names and the actual values of formulas //DataTable dt = worksheet.ExportDataTable(worksheet.Range["A1:C10"], true, true); dataGridView1.DataSource = dt; }
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.