Below code works, but three minor issues:
1) No title row, how can I copy title row too (I mean field name row).
2) The data is pasted to cell B2, so output file column A is blank. It seems that the code also try to copy the blank grayed out column(with arrow and * ).
3) What is the code to deselect the datagridview table(after pasting the data to excel)?
Thanks.
private void pictureboxExcelExport_Click(object sender, EventArgs e)
{
copyAlltoClipboard();
Microsoft.Office.Interop.Excel.Application xlexcel;
Microsoft.Office.Interop.Excel.Workbook xlWorkBook;
Microsoft.Office.Interop.Excel.Worksheet xlWorkSheet;
object misValue = System.Reflection.Missing.Value;
xlexcel = new Microsoft.Office.Interop.Excel.Application();
xlexcel.Visible = true;
xlWorkBook = xlexcel.Workbooks.Add(misValue);
xlWorkSheet = (Microsoft.Office.Interop.Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
Microsoft.Office.Interop.Excel.Range CR = (Microsoft.Office.Interop.Excel.Range)xlWorkSheet.Cells[1, 1];
CR.Select();
xlWorkSheet.PasteSpecial(CR, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, true);
}
private void copyAlltoClipboard()
{
dgvTest.SelectAll();
DataObject dataObj = dgvTest.GetClipboardContent();
if (dataObj != null)
Clipboard.SetDataObject(dataObj);
}