Click here to Skip to main content
15,902,905 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I have a datagridview and a dataset,
i wish to export the datagridview rows in Excel,CSV,PDF, format by clicking on the export button..

i know nothing about it....please tell me step by step procedure to get it done..

what com component i have to include in my toolbox..
and what is the Excel Application .net 2008 c#

1 solution

You can write a datatable to a text file with code as follows

In the example below, FieldDelimiter is a const in a class - you can choose what to use (e.g maybe pipe | or tilde ~ or comma ,)

private static string WriteToTextFile(System.Data.DataTable data)
    string fileName = System.IO.Path.GetTempFileName();
    using (FileStream fs = new System.IO.FileStream(fileName, FileMode.Create))
        using (StreamWriter sw = new StreamWriter(fs, System.Text.Encoding.Unicode))
            string columnHeaders = string.Empty;
            for (int i = 0; i < data.Columns.Count; ++i)
                columnHeaders += data.Columns[i].Caption + (i < data.Columns.Count - 1 ? FieldDelimiter : string.Empty);
            // Write the field names (headers) as the first line in the text file.
            foreach (DataRow row in data.Rows)
                for (int i = 0; i < data.Columns.Count; ++i)
                    string s = row[i].ToString() + (i < data.Columns.Count - 1 ? FieldDelimiter : string.Empty);
            sw.Flush(); // Write the buffered data to the filestream.
            // Close the FileStream.
            return fileName;

Exporting to excel can be done in a number of ways. One is simply to automate Excel and write the contents of the DataTable into the excel workbook. e.g have a look here[^]

I find this method has a performance hit, I get better performance by using the WriteToTextFile code above, then importing the entire text file into Excel.

e.g something like

private static Workbook CreateWorkbookFromTextfile(Microsoft.Office.Interop.Excel.Application excel, string fileName)
    Workbooks books = null;
    Workbook workbook = null;

        books = excel.Workbooks;

            XlPlatform.xlWindows, 1,
            false, false, false, false, false, true,
            FieldDelimiter, Missing.Value,
            Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value);

        workbook = books.get_Item(1);
        return workbook;
        #region COM Interop Cleanup Code


That should help you get started with Excel & CSV file, PDF is a different question though
Share this answer
MalwareTrojan 18-Feb-13 5:49am    
If i want only for spreadsheet then how it should go?

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