Andy Schmitt Andy Schmitt -4 years ago 364
C# Question

C# Windows Forms Export to Excel

I have a simple application.
My application loads a csv, alter some data and exports to excel.


When I click "Exportar..." it exports.
The code is following.

private void cmdExport_Click(object sender, EventArgs e)
cmdExport.Enabled = false;
cmdSelecionar.Enabled = false;

//Copy DataGridView to clipboard
dgvMain.ClipboardCopyMode = DataGridViewClipboardCopyMode.EnableAlwaysIncludeHeaderText;
dgvMain.MultiSelect = true;

DataObject dataObj = dgvMain.GetClipboardContent();
if (dataObj != null)

//Open an excel instance and paste the copied data
Excel.Application xlexcel;
Excel.Workbook xlWorkBook;
Excel.Worksheet xlWorkSheet;
object misValue = System.Reflection.Missing.Value;
xlexcel = new Excel.Application();
xlexcel.Visible = true;
xlWorkBook = xlexcel.Workbooks.Add(misValue);
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
Excel.Range CR = (Excel.Range)xlWorkSheet.Cells[1, 1];
xlWorkSheet.PasteSpecial(CR, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, true);

cmdSelecionar.Enabled = true;

When I export, it adds a blank column in the begining, the "A" column.
Why this is happening?
Whats wrong with my code?

The excel print follows:

Excel exported

Answer Source

You have row headers on your DataGridView, you can see it in your image as the light blue highlighted column with the > arrow at the top.

If you don't need them you can disable them with dgvMain.RowHeadersVisible = false;

Alternatively you could delete the first column after pasting:

Excel.Range range = (Excel.Range)xlWorkSheet.get_Range("A1", Missing.Value);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download