Andy Schmitt
Andy Schmitt

Reputation: 393

C# Windows Forms Export to Excel

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

Application

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;
        dgvMain.SelectAll();

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

        //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];
        CR.Select();
        xlWorkSheet.PasteSpecial(CR, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, true);

        cmdSelecionar.Enabled = true;
    }

Problem: 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

Upvotes: 1

Views: 4504

Answers (3)

koteswara rao
koteswara rao

Reputation: 1

Can you check if the following works:

Excel.Range CR = (Excel.Range)xlWorkSheet.Cells[A1, 1];
Excel.Range CR = (Excel.Range)xlWorkSheet.Cells[0, 1];

Upvotes: 0

Ross Miller
Ross Miller

Reputation: 646

You are pasting from the clipboard which is fine, but I suspect your data in the clipboard contains a blank column.

Upvotes: 0

Equalsk
Equalsk

Reputation: 8194

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);
range.EntireColumn.Delete(Missing.Value);

Upvotes: 2

Related Questions