Question

I wrote a exporting function so that all the data from my datagridview gets exported into an Excel file when I click on a button. Now this throws me one problem, I want to define the column widths of my excel columns. At the moment when I open my Excel I always get ######## in the column of my dates. This is due too the column not being wide enough.

Example of how it looks in Excel:

So without further ado, this is my code.

private void excelToolStripMenuItem_Click(object sender, EventArgs e)
{
    SaveFileDialog sfd = new SaveFileDialog();

    sfd.Filter = "Excel Documents (*.xls)|*.xls";

    sfd.FileName = "reminders_MM.xls"; // Default File Name

    if (sfd.ShowDialog() == DialogResult.OK)
    {
        ToCsV(dataGridViewReminders, sfd.FileName);
    }
    MessageBox.Show("Alle data is succesvol geëxporteerd!", "Voltooid", MessageBoxButtons.OK, MessageBoxIcon.Information);
}

private void ToCsV(DataGridView dgv, string filename)
{
    string stOutput = "";
    // Export titles:
    string sHeaders = "";

    for (int j = 2; j < dgv.Columns.Count; j++)
        sHeaders = sHeaders.ToString() + Convert.ToString(dgv.Columns[j].HeaderText) + "\t";
        stOutput += sHeaders + "\r\n";
        // Export data.
        for (int i = 0; i <= dgv.RowCount - 1; i++)
        {
            string stLine = "";
            for (int j = 2; j < dgv.Rows[i].Cells.Count; j++)
                stLine = stLine.ToString() + Convert.ToString(dgv.Rows[i].Cells[j].Value) + "\t";
                stOutput += stLine + "\r\n";
            }
        }  
    }

    Encoding utf16 = Encoding.GetEncoding(1254);
    byte[] output = utf16.GetBytes(stOutput);
    FileStream fs = new FileStream(filename, FileMode.Create);
    BinaryWriter bw = new BinaryWriter(fs);
    bw.Write(output, 0, output.Length); //write the encoded file
    bw.Flush();
    bw.Close();
    fs.Close();
}

The question is simple. How can I define the width of my columns that will come into my Excel file? I want every column to be far wider.

Was it helpful?

Solution

I do not believe there is a way to do what you want without using Office Interop. With .NET 4.0 you'll find Excel Interop is not that bad. For instance, to accomplish autofit for columns, it would look like this.

worksheet.Cells.Style.EntireColumn.AutoFit()

A good Office Interoperability for Excel starter can be found here.

Edit: There is an alternative to Office Interop. See davmos' answer.

OTHER TIPS

If you're using Excel 2007 or later, the preferred alternative to COM Interop is the Open XML SDK. There is a nice walk-through at Using C# and Open XML SDK 2.0 for Microsoft Office to Create an Excel 2007 Document.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top