Currently using the Excel print function to Export data from a WPF Datagrid and print it. Below is the code I am using:
private void OnDataGridPrinting(object sender, RoutedEventArgs e)
{
System.Windows.Controls.PrintDialog Printdlg = new System.Windows.Controls.PrintDialog();
if ((bool)Printdlg.ShowDialog().GetValueOrDefault())
{
// creating Excel Application
Microsoft.Office.Interop.Excel._Application app = new Microsoft.Office.Interop.Excel.Application();
// creating new WorkBook within Excel application
Microsoft.Office.Interop.Excel._Workbook workbook = app.Workbooks.Add(Type.Missing);
// creating new Excelsheet in workbook
Microsoft.Office.Interop.Excel._Worksheet worksheet = null;
// see the excel sheet behind the program
app.Visible = false;
// get the reference of first sheet. By default its name is Sheet1.
// store its reference to worksheet
worksheet = workbook.Sheets["Sheet1"];
worksheet = workbook.ActiveSheet;
// changing the name of active sheet
worksheet.Name = SelectedCustomer.CustName;
// storing header part in Excel
CollectionViewSource itemCollectionViewSources;
itemCollectionViewSources = (CollectionViewSource)(FindResource("ItemCollectionViewSources"));
for (int i = 1; i < dgEndOfYear.Columns.Count + 1; i++)
{
**worksheet.Cells[1, i] = dgEndOfYear.Columns[i - 1].Header;**
}
// storing Each row and column value to excel sheet
for (int i = 0; i < CustomerEOYTotals.Count - 0; i++)
{
absvwEndOfYearTotal1 line = CustomerEOYTotals[i];
worksheet.PageSetup.CenterHeader = "&UEnd Of Year Report " + CurrentYear;
worksheet.Cells[i + 2, 1] = line.CalendarYear;
worksheet.Cells[i + 2, 2] = line.CustName;
worksheet.Cells[i + 2, 3] = line.MonthName;
worksheet.Cells[i + 2, 4] = line.SumGal.Value.ToString();
worksheet.Cells[i + 2, 5] = line.Manifest;
worksheet.Columns.Cells.Font.FontStyle = Microsoft.Office.Interop.Excel.XlUnderlineStyle.xlUnderlineStyleSingle;
worksheet.Cells.Style.HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignCenter;
worksheet.Columns.ColumnWidth = 14;
}
// Print the workbook
workbook.PrintOut();
The line "worksheet.Cells[1, i] = dgEndOfYear.Columns[i - 1].Header" are the headers from the data grid I have made several attempts to style the headers so they are underlined like the below example when printed out but have had no luck any help would be appreciated: