Hello, tell me how to import data from Excel into a WPF DataGrid table. Thanks in advance. enter image description here

  • If the table view is known in advance, it is convenient to create your own data type. Further read from the file as from any other. - user227049
  • Your task essentially consists of two - load data from an Excel file and display the data in a DataGrid. Which of these tasks you fail? If both - it is worth making them separate issues - Andrew NOP
  • Thanks for the answer, I really get two tasks. - Eugene
  • which one is the problem? - user227049
  • Hello, in general, there is a problem to load exactly excel into the datagrid wpf table, I just don’t understand this. Or at least what I found is how to load excel into a form, but without the participation of the datagrid table. - Eugene

1 answer 1

In general, such questions should be closed as too general, with all my persuasions you did not break the task into parts and did not write what exactly you have in every small part of the task. I will risk you to answer and write down how to break the task into parts and implement each part.

So, for a start, the task is divided into two smaller ones:

  1. Read data from excel
  2. Displaying data in a GUI

1. Reading data from Excel

For convenience and speed up debugging of this part, it is easier to first create a console project, rather than WPF. That is what I will do.

First of all, you need to create model classes, instances of which you will create on the basis of data from an Excel workbook. I will assume that you have one row in the table represents one kind of object (if this is not the case, you should create other classes and data structures that are more appropriate):

public class Metric { public int Alpha { get; set; } public int Beta { get; set; } public int Gamma { get; set; } public int Delta { get; set; } } 

Next, you need to create a method that loads data from Excel and returns a collection of Metric instances. We need a tool for working with Excel, I hope that you use a newer xlsx-format of books, so I will describe how you can work with it. I connected ClosedXml package from NuGet (documentation and examples for it are somewhere here ) and wrote this method:

 using ClosedXML.Excel; using System.Collections.Generic; ... static IEnumerable<Metric> EnumerateMetrics(string xlsxpath) { // Открываем книгу using (var workbook = new XLWorkbook(xlsxpath)) // Берем в ней первый лист using (var worksheet = workbook.Worksheets.Worksheet(1)) { // Перебираем диапазон нужных строк for (int row = 2; row <= 3; ++row) { // По каждой строке формируем объект var metric = new Metric { Alpha = worksheet.Cell(row, 1).GetValue<int>(), Beta = worksheet.Cell(row, 2).GetValue<int>(), Gamma = worksheet.Cell(row, 3).GetValue<int>(), Delta = worksheet.Cell(row, 4).GetValue<int>(), }; // И возвращаем его yield return metric; } } } 

Perhaps, in addition to the file path, you will also need to transfer the sheet number and cell coordinates from which you need to load data into the EnumerateMetrics method, while this is all a hard-coded data item.

Ok, test the method:

 static void Main(string[] args) { var metrics = EnumerateMetrics("Data.xlsx"); foreach (var m in metrics) Console.WriteLine("Альфа: {0}; Бета: {1}; Гамма: {2}; Дельта: {3}", m.Alpha, m.Beta, m.Gamma, m.Delta); Console.ReadKey(); } 

Hooray! This part is working fine!

2. Displaying data in a GUI

Now you can finally create a WPF project and lay out the main window. I ask you, you don’t need to "draw controls with the mouse", write the markup manually, this will make it more concise, more flexible, and you will benefit from this - you will quickly understand the meaning of all this. So, we need a Grid with two columns, in the first we put the DataGrid , and in the second Button . I will not give you the "fill in the head" of MVVM and other things now, so we simply give the control names in the markup and subscribe to the click event of the button:

 <Grid Margin="5"> <Grid.ColumnDefinitions> <ColumnDefinition/> <ColumnDefinition Width="100"/> </Grid.ColumnDefinitions> <DataGrid Name="MetricsDataGrid" Margin="0,0,5,0"/> <Button Grid.Column="1" VerticalAlignment="Top" Padding="10,5" Click="Button_Click"> <TextBlock TextAlignment="Center" TextWrapping="Wrap" Text="Загрузить таблицу"/> </Button> </Grid> 

It looks good.

Now, from the past project, we copy into this our class Metric and the EnumerateMetrics method, but since it cannot exist by itself, let's create a class, for example XlsxHelper and put this method into it and make it public. Well, do not forget, of course, to connect the package ClosedXml.

It remains only to use the previously written code in the click handler for the button:

 private void Button_Click(object sender, RoutedEventArgs e) { var metrics = XlsxHelper.EnumerateMetrics("Data.xlsx").ToList(); MetricsDataGrid.ItemsSource = metrics; } 

Well, to make the columns in DataGrid look nicer, turn off autogeneration and create them manually:

 <DataGrid Name="MetricsDataGrid" Margin="0,0,5,0" AutoGenerateColumns="False"> <DataGrid.Columns> <DataGridTextColumn Header="Альфа" Binding="{Binding Alpha}"/> <DataGridTextColumn Header="Бета" Binding="{Binding Beta}"/> <DataGridTextColumn Header="Гамма" Binding="{Binding Gamma}"/> <DataGridTextColumn Header="Дельта" Binding="{Binding Delta}"/> </DataGrid.Columns> </DataGrid> 

screen

  • Thank you very much, I will try now, I apologize, I edited the written message by me, but apparently did not save the editing and now I see that everything I wrote remained as it was. - Eugene
  • Thank you very much, I suffered a lot for a long time, but I still achieved the result, I figured out the console application once, but I couldn’t find a typo for a long time with wpf. In general, I am amazed at how much effort I need and understand rational logic in programming, let's say that given my concept I would have been given out somewhere in three four months and then with many errors. Thanks a lot!!!!!! - Eugene
  • @ Eugene, please, glad to help. A year of training and you can write such code without any problems. If your question is resolved, tick the answer (it is on the left below the buttons for voting). - Andrei NOP