Click here to Skip to main content
15,891,881 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
See more:
Hi i'm working with Visual C# and i've a method that exports a DataGridView to an Excel File, my question is how can I give format to the Excel file so it looks better, like making the headers look bold, and coloured with blue, etc.

The method that i'm using is this:
C#
            /// <summary>
            /// Exports a passed datagridview to an Excel worksheet.
            /// If captions is true, grid headers will appear in row 1.
            /// Data will start in row 2.
            /// </summary>
            /// <param name="datagridview"></param>
            /// <param name="captions"></param>
public static void Excel(DataGridView datagridview, bool captions = true)
            {
                object objApp_Late;
                object objBook_Late;
                object objBooks_Late;
                object objSheets_Late;
                object objSheet_Late;
                object objRange_Late;
                object[] Parameters;
                string[] headers = new string[datagridview.ColumnCount];
                string[] columns = new string[datagridview.ColumnCount];

                int i = 0;
                int c = 0;
                for (c = 0; c < datagridview.ColumnCount; c++)
                {
                    headers[c] = datagridview.Rows[0].Cells[c].OwningColumn.Name.ToString();
                    i = c + 65;
                    columns[c] = Convert.ToString((char)i);
                }

                try
                {
                    // Get the class type and instantiate Excel.
                    Type objClassType;
                    objClassType = Type.GetTypeFromProgID("Excel.Application");
                    objApp_Late = Activator.CreateInstance(objClassType);
                    //Get the workbooks collection.
                    objBooks_Late = objApp_Late.GetType().InvokeMember("Workbooks",
                    BindingFlags.GetProperty, null, objApp_Late, null);
                    //Add a new workbook.
                    objBook_Late = objBooks_Late.GetType().InvokeMember("Add",
                    BindingFlags.InvokeMethod, null, objBooks_Late, null);
                    //Get the worksheets collection.
                    objSheets_Late = objBook_Late.GetType().InvokeMember("Worksheets",
                    BindingFlags.GetProperty, null, objBook_Late, null);
                    //Get the first worksheet.
                    Parameters = new Object[1];
                    Parameters[0] = 1;
                    objSheet_Late = objSheets_Late.GetType().InvokeMember("Item",
                    BindingFlags.GetProperty, null, objSheets_Late, Parameters);

                    if (captions)
                    {
                        // Create the headers in the first row of the sheet
                        for (c = 0; c < datagridview.ColumnCount; c++)
                        {
                            //Get a range object that contains cell.
                            Parameters = new Object[2];
                            Parameters[0] = columns[c] + "1";
                            Parameters[1] = Missing.Value;
                            objRange_Late = objSheet_Late.GetType().InvokeMember("Range",
                            BindingFlags.GetProperty, null, objSheet_Late, Parameters);
                            //Write Headers in cell.
                            Parameters = new Object[1];
                            Parameters[0] = headers[c];
                            objRange_Late.GetType().InvokeMember("Value", BindingFlags.SetProperty,
                            null, objRange_Late, Parameters);
                        }
                    }

                    // Now add the data from the grid to the sheet starting in row 2
                    for (i = 0; i < datagridview.RowCount; i++)
                    {
                        for (c = 0; c < datagridview.ColumnCount; c++)
                        {
                            //Get a range object that contains cell.
                            Parameters = new Object[2];
                            Parameters[0] = columns[c] + Convert.ToString(i + 2);
                            Parameters[1] = Missing.Value;
                            objRange_Late = objSheet_Late.GetType().InvokeMember("Range",
                            BindingFlags.GetProperty, null, objSheet_Late, Parameters);
                            //Write Headers in cell.
                            Parameters = new Object[1];
                            Parameters[0] = datagridview.Rows[i].Cells[headers[c]].Value.ToString();
                            objRange_Late.GetType().InvokeMember("Value", BindingFlags.SetProperty,
                            null, objRange_Late, Parameters);
                        }
                    }

                    //Return control of Excel to the user.
                    Parameters = new Object[1];
                    Parameters[0] = true;
                    objApp_Late.GetType().InvokeMember("Visible", BindingFlags.SetProperty,
                    null, objApp_Late, Parameters);
                    objApp_Late.GetType().InvokeMember("UserControl", BindingFlags.SetProperty,
                    null, objApp_Late, Parameters);
                }
                catch (Exception theException)
                {
                    String errorMessage;
                    errorMessage = "Error: ";
                    String.Format("{0} {1} {2}", theException.Message, "Line:", theException.Source);

                    MessageBox.Show(errorMessage, "Error");
                }
            }


Thanks in advance.
Best Regards.
Posted
Updated 16-Dec-10 11:31am
v3
Comments
E.F. Nijboer 16-Dec-10 11:37am    
Just as side note:
Did you know String.Concat isn't limited t just one addition?
http://msdn.microsoft.com/en-us/library/0eafbze3.aspx
...or for this exception handler String.Format:
http://msdn.microsoft.com/en-us/library/d9t40k6d.aspx
Pablinff 16-Dec-10 16:50pm    
I'm sorry, I do not understand in what way this can be helpful for me. I'm just too newbie in C# .NET.
Thanks anyway E.F. Nijboer
fjdiewornncalwe 16-Dec-10 17:24pm    
It means where you build your error message can be done in a simpler way.
errorMessage = String.Format( "{0} {1} {2}", theException.Message, "Line:", theException.Source );
Pablinff 16-Dec-10 17:29pm    
Oh! That improves the method! Thanks!! Updated!
And... any idea about formatting the excel file?
Cheers!!
Sergey Alexandrovich Kryukov 16-Dec-10 19:43pm    
Marcus, Pablinff,

string errorMessage = String.Format( "{0} {1} {2}", theException.Message, "Line:", theException.Source);
should really be:
string errorMessage = string.Format( "{0}, line: {1}", theException.Message, theException.Source);
(Also, it's often useful to show theException.GetType().Name, sometimes InnerException and StackTrace.)

As this comments has something to do with the code of Pablinff, you note on Concat is quite irrelevant (why not to describe Join, Compare, etc.?).

Thanks anyway.

1 solution

It looks like you can control the formatting by using the DisplayFormat[^] property of the Range object.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900