简体   繁体   中英

How to transfer data from Excel to a DataGridView in C#?

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.

You should convert your Excel-File to a C#-Object, like a List, DataTable, or something else that you can bind to a DataGridView.

Check out CsvHelper , this might get you started.

Then, simply bind to your Object to your DataGridView, eg how it was shown here .

Good Luck!

  1. Right-click on your project's name or References and select Manage NuGet Packages . 在此处输入图像描述

  2. Under the Browse tab, search for free spire.xls and install it. 在此处输入图像描述

  3. 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM