I am trying to import an excel file to a datagrid in WPF. What I've found around the Internet won't rally do the trick.
I have a code that opens and reads excelfiles and outputs the data cells to a messagebox. I want to do so but to DataGrid instead. Here follows the code that needs to be changed:
private void ReadFromFile_Click(object sender, RoutedEventArgs e) { //Create COM Objects. Create a COM object for everything that is referenced Excel.Application xlApp = new Excel.Application(); Excel.Workbook xlWorkbook = xlApp.Workbooks.Open(@"C:\Temp\vitoshacademy.xlsx"); Excel._Worksheet xlWorksheet = xlWorkbook.Sheets[1]; Excel.Range xlRange = xlWorksheet.UsedRange; int rowCount = xlRange.Rows.Count; int colCount = xlRange.Columns.Count; //iterate over the rows and columns and print to the console as it appears in the file //excel is not zero based!! for (int i = 1; i <= rowCount; i++) { for (int j = 1; j <= colCount; j++) { //new line if (j == 1) MessageBox.Show("\r\n"); //write the value to the console if (xlRange.Cells[i, j] != null && xlRange.Cells[i, j].Value2 != null) MessageBox.Show(xlRange.Cells[i, j].Value2.ToString() + "\t"); } } //cleanup GC.Collect(); GC.WaitForPendingFinalizers(); //rule of thumb for releasing com objects: // never use two dots, all COM objects must be referenced and released individually // ex: [somthing].[something].[something] is bad //release com objects to fully kill excel process from running in the background Marshal.ReleaseComObject(xlRange); Marshal.ReleaseComObject(xlWorksheet); //close and release xlWorkbook.Close(); Marshal.ReleaseComObject(xlWorkbook); //quit and release xlApp.Quit(); Marshal.ReleaseComObject(xlApp); }