Encapsulated into a class for later use (export datagrid)
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Controls; namespace AstroATE { class ExportToExcel { public bool Export(DataGrid dataGrid, string excelTitle) { System.Data.DataTable dt = new System.Data.DataTable(); for (int i = 0; i < dataGrid.Columns.Count; i++) { if (dataGrid.Columns[i].Visibility == System.Windows.Visibility.Visible)//Export only visible columns { dt.Columns.Add(dataGrid.Columns[i].Header.ToString());//Build the header } } for (int i = 0; i < dataGrid.Items.Count; i++) { int columnsIndex = 0; System.Data.DataRow row = dt.NewRow(); for (int j = 0; j < dataGrid.Columns.Count; j++) { if (dataGrid.Columns[j].Visibility == System.Windows.Visibility.Visible) { if (dataGrid.Items[i] != null && (dataGrid.Columns[j].GetCellContent(dataGrid.Items[i]) as TextBlock) != null)//Fill visible column data { row[columnsIndex] = (dataGrid.Columns[j].GetCellContent(dataGrid.Items[i]) as TextBlock).Text.ToString(); } else row[columnsIndex] = ""; columnsIndex++; } } dt.Rows.Add(row); } if(ExcelExport(dt, excelTitle) != null) { return true; } else { return false; } } public string ExcelExport(System.Data.DataTable DT, string title) { try { //Create Excel Microsoft.Office.Interop.Excel.Application ExcelApp = new Microsoft.Office.Interop.Excel.Application(); Microsoft.Office.Interop.Excel.Workbook ExcelBook = ExcelApp.Workbooks.Add(System.Type.Missing); //Create a worksheet (that is, a sub-sheet in Excel) 1 means export data in the sub-sheet sheet1 Microsoft.Office.Interop.Excel.Worksheet ExcelSheet = (Microsoft.Office.Interop.Excel.Worksheet)ExcelBook.Worksheets[1]; //If there is a numeric type in the data, it can be displayed in text format ExcelSheet.Cells.NumberFormat = "@"; //set the worksheet name ExcelSheet.Name = title; //Set Sheet title string start = "A1"; string end = ChangeASC(DT.Columns.Count) + "1"; Microsoft.Office.Interop.Excel.Range _Range = (Microsoft.Office.Interop.Excel.Range)ExcelSheet.get_Range(start, end); _Range.Merge(0); //Cell merge action (to be designed with get_Range() above) _Range = (Microsoft.Office.Interop.Excel.Range)ExcelSheet.get_Range(start, end); _Range.HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignCenter; _Range.Font.Size = 22; //Set the font size _Range.Font.Name = "宋体"; //Set the type of font ExcelSheet.Cells[1, 1] = title; //Excel cell assignment _Range.EntireColumn.AutoFit(); //Automatically adjust the column width //write header for (int m = 1; m <= DT.Columns.Count; m++) { ExcelSheet.Cells[2, m] = DT.Columns[m - 1].ColumnName.ToString(); start = "A2"; end = ChangeASC(DT.Columns.Count) + "2"; _Range = (Microsoft.Office.Interop.Excel.Range)ExcelSheet.get_Range(start, end); _Range.Font.Size = 15; //Set the font size _Range.Font.Bold = true;//Bold _Range.Font.Name = "宋体"; //Set the type of font _Range.EntireColumn.AutoFit(); //Automatically adjust the column width _Range.HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignCenter; } //write data for (int i = 0; i < DT.Rows.Count; i++) { for (int j = 1; j <= DT.Columns.Count; j++) { //The first Excel cell starts at index 1 // if (j == 0) j = 1; ExcelSheet.Cells[i + 3, j] = DT.Rows[i][j - 1].ToString(); } } // table property settings for (int n = 0; n < DT.Rows.Count + 1; n++) { start = "A" + (n + 3).ToString(); end = ChangeASC(DT.Columns.Count) + (n + 3).ToString(); //Get multiple cell ranges in Excel _Range = (Microsoft.Office.Interop.Excel.Range)ExcelSheet.get_Range(start, end); _Range.Font.Size = 12; //Set the font size _Range.Font.Name = "宋体"; //Set the type of font _Range.EntireColumn.AutoFit(); //Automatically adjust the column width _Range.HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignCenter; //Set the alignment of the font in the cell _Range.EntireColumn.AutoFit(); //Automatically adjust the column width } ExcelApp.DisplayAlerts = false; //When saving Excel, save the window without popping up whether to save or not // Pop up the save dialog and save the file Microsoft.Win32.SaveFileDialog sfd = new Microsoft.Win32.SaveFileDialog(); sfd.DefaultExt = ".xlsx"; sfd.Filter = "Office 2007 File|*.xlsx|Office 2000-2003 File|*.xls|All Files|*.*"; if (sfd.ShowDialog() == true) { if (sfd.FileName != "") { ExcelBook.SaveAs(sfd.FileName); //Save it to the specified path // MessageBox.Show("The export file has been stored as: " + sfd.FileName, "Warm reminder"); } } // release processes that may not have been released ExcelBook.Close(); ExcelApp.Quit(); // PubHelper.Instance.KillAllExcel(ExcelApp); return sfd.FileName; } catch { // MessageBox.Show("Failed to save export file!", "Warning!"); return null; } } /// <summary> /// Get the current column column name and get the corresponding column in EXCEL /// </summary> /// <param name="count"></param> /// <returns></returns> private string ChangeASC(int count) { string ascstr = ""; switch (count) { case 1: ascstr = "A"; break; case 2: ascstr = "B"; break; case 3: ascstr = "C"; break; case 4: ascstr = "D"; break; case 5: ascstr = "E"; break; case 6: ascstr = "F"; break; case 7: ascstr = "G"; break; case 8: ascstr = "H"; break; case 9: ascstr = "I"; break; case 10: ascstr = "J"; break; case 11: ascstr = "K"; break; case 12: ascstr = "L"; break; case 13: ascstr = "M"; break; case 14: ascstr = "N"; break; case 15: ascstr = "O"; break; case 16: ascstr = "P"; break; case 17: ascstr = "Q"; break; case 18: ascstr = "R"; break; case 19: ascstr = "S"; break; case 20: ascstr = "Y"; break; default: ascstr = "U"; break; } return ascstr; } } }