private void Btn_Export_Click(object sender, EventArgs e) { try { Microsoft.Office.Interop.Excel.Application xlapp = new Microsoft.Office.Interop.Excel.Application(); Microsoft.Office.Interop.Excel.Workbook xlWorkBook; Microsoft.Office.Interop.Excel.Worksheet xlsheet; //Create object of excel xlWorkBook = (Microsoft.Office.Interop.Excel.Workbook)xlapp.Workbooks.Add(1); xlsheet = (Microsoft.Office.Interop.Excel.Worksheet)xlWorkBook.ActiveSheet; int i = 0; int j = 0; for (i = 0; i < datagridView.Columns.Count; i++) { xlsheet.Cells[1, i+1] = datagridView.Columns[i].HeaderText; } for (i = 0; i < datagridView.RowCount; i++) { for (j = 0; j < datagridView.ColumnCount; j++) { xlsheet.Cells[i+2, j+1] = datagridView.Rows[i].Cells[j].Value; } } xlapp.Visible = true; Microsoft.Office.Interop.Excel.Range myRange = xlsheet.get_Range(xlsheet.Cells[1, 1], xlsheet.Cells[this.datagridView.RowCount + 1, this.datagridView.Columns.Count]); Microsoft.Office.Interop.Excel.Font x = myRange.Font; //set bold font to column header myRange = xlsheet.get_Range(xlsheet.Cells[1, 1], xlsheet.Cells[1, this.datagridView.Columns.Count]); x = myRange.Font; x.Bold = true; //autofit all columns myRange.EntireColumn.AutoFit(); myRange.HorizontalAlignment = Excel.XlHAlign.xlHAlignCenter; } catch (Exception ex) { MessageBox.Show(ex.ToString(), "Error"); return; } }
var
This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)