Visual Studio .NET - Export to CSV format

Asked By vamsi n
24-Oct-08 06:18 AM

Hi All
i am using Asp.Net2.0 & c#
i exported the dataset to csv format

in .aspx page
----------------

 private void csvExport()
    {
        string strConn = System.Configuration.ConfigurationSettings.AppSettings["ConnStr"].ToString();
        SqlConnection conn = new SqlConnection(strConn);
        SqlDataAdapter da = new SqlDataAdapter("select kanr,jahr,monat  from prsadmin.kst_monat", conn);
        DataSet ds1 = new DataSet();
        da.Fill(ds1, "Emp");
        CSVHelper csv = new CSVHelper();
        string strData = csv.Export(ds1, true);
        System.Text.Encoding enc = System.Text.Encoding.ASCII;
        byte[] data = System.Text.Encoding.UTF8.GetBytes(strData);
        Response.Clear();
        Response.AddHeader("Content-Type", "Application/x-msexcel");
        Response.AddHeader("Content-Disposition", "attachment;filename=PrintCSV.csv");
        Response.BinaryWrite(data);
        Response.End();
        Response.Close();
       

    }

in .cs file
--------------
 public string Export(DataSet ds, bool exportColumnHeadings)
        {
            string header = string.Empty;
            string body = string.Empty;
            string record = string.Empty;// If you want column to be part of the CSV ...
            if (exportColumnHeadings)
            {
                foreach (DataColumn col in ds.Tables[0].Columns)
                {
                    header = header + (char)34 + col.ColumnName + (char)34 + ",";
                }
                header = header.Substring(0, header.Length - 1);
            }// Iterate into the rows
            foreach (DataRow row in ds.Tables[0].Rows)
            {
                Object[] arr = row.ItemArray;
                for (int i = 0; i <= arr.Length - 1; i++)
                {
                    if (arr[i].ToString().IndexOf(",") > 0)
                    {
                        record = record + (char)34 + arr[i].ToString() + (char)34 + ",";
                    }
                    else
                    {
                        record = record + arr[i].ToString() + ",";
                    }
                }
                body = body + record.Substring(0, record.Length - 1) + Environment.NewLine;
                record = "";
            }
            if (exportColumnHeadings)
            {
                return (header + Environment.NewLine + body);
            }
            else
            {
                return body;
            }
        }

---------
it exported to CSV file but it shows the data as Excel format(ie: seperate cells) it does not combined the data with commas(,)

please help me

Thanking you
Vamsi.

Reply  Reply

24-Oct-08 06:27 AM
Tells you how to export a DataSet's DataTable to CSV (excel readable) format.
.NET Classes used :
  • DataTableHelper
  • System.IO.StreamWriter
  • System.Data.DataTable
  • using System;
    using System.Data;
    using System.IO;

    public class DataTableHelper
    {

    ///
    /// Can stream DataTable to Browser, directly, you need to set
    ///
    /// Response.Clear();
    /// Response.Buffer= true;
    /// Response.ContentType = "application/vnd.ms-excel";
    /// Response.AddHeader("Content-Disposition", "inline;filename=Clientes.xls"); Response.Charset = "";
    /// this.EnableViewState = false
    /// // ACTUAL CODE
    /// ProduceCSV(dt, Response.Output, true);
    ///
    public static void ProduceCSV(DataTable dt, System.IO.TextWriter httpStream, bool WriteHeader)
    {
    if(WriteHeader)
    {
    string[] arr = new String[dt.Columns.Count];
    for(int i = 0; i<dt.Columns.Count; i++)
    {
    arr[i] = dt.Columns[i].ColumnName;
    arr[i] = GetWriteableValue(arr[i]);
    }

    httpStream.WriteLine(string.Join(",", arr));
    }

    for(int j = 0; j<dt.Rows.Count; j++)
    {
    string[] dataArr = new String[dt.Columns.Count];
    for(int i = 0; i<dt.Columns.Count; i++)
    {
    object o = dt.Rows[j][i];
    dataArr[i] = GetWriteableValue(o);
    }
    httpStream.WriteLine(string.Join(",", dataArr));
    }
    }

    #region CSV Producer
    public static void ProduceCSV(DataTable dt, System.IO.StreamWriter file, bool WriteHeader)
    {
    if(WriteHeader)
    {
    string[] arr = new String[dt.Columns.Count];
    for(int i = 0; i<dt.Columns.Count; i++)
    {
    arr[i] = dt.Columns[i].ColumnName;
    arr[i] = GetWriteableValue(arr[i]);
    }

    file.WriteLine(string.Join(",", arr));
    }

    for(int j = 0; j<dt.Rows.Count; j++)
    {
    string[] dataArr = new String[dt.Columns.Count];
    for(int i = 0; i<dt.Columns.Count; i++)
    {
    object o = dt.Rows[j][i];
    dataArr[i] = GetWriteableValue(o);
    }
    file.WriteLine(string.Join(",", dataArr));
    }
    }

    public static string GetWriteableValue(object o)
    {
    if(o==null || o == Convert.DBNull)
    return "";
    else if(o.ToString().IndexOf(",")==-1)
    return o.ToString();
    else
    return "\"" + o.ToString() + "\"";

    }
    #endregion
    }

    read this code  read this code

    24-Oct-08 09:48 AM

    This can be used in WebForms as well as in WinForms by simply passing a parameter to the export object's constructor.

    • For WebForms:
      RKLib.ExportData.Export objExport = new RKLib.ExportData.Export("Web")
    • For WinForms:
      RKLib.ExportData.Export objExport = new RKLib.ExportData.Export("Win")

    The ExportDetails method has three types of overloads. You can call whichever best suits your requirement.

    The following are the overload types:

    • public void ExportDetails(DataTable DetailsTable, 
      ExportFormat FormatType, string FileName)
    • public void ExportDetails(DataTable DetailsTable, int[] 
      ColumnList, ExportFormat FormatType, string FileName)
    • public void ExportDetails(DataTable DetailsTable, int[] 
      ColumnList, string[] Headers, ExportFormat FormatType, string FileName)

    Have a glance at the parameters

    • DetailsTable - DataTable to be exported.
    • FormatType - Export File Format. Use Export.ExportFormat.CSV for the CSV file or Export.ExportFormat.Excel for the Excel file.
    • FileName - Export File Name.
      - For WebForms simply pass the filename. e.g. EmployeeInfo.xls
      - For WinForms pass the filename along with path. e.g. C:\\EmployeeInfo.csv
    • ColumnList - DataFields of the DataTable to be exported. Specify their ordinals in an integer array.
    • Headersrs - Custom Headers List for the specified columns in the export file. Specify the names in a string array.

    You can call this method in the: ASPButton_Click event, LinkButton_Click event or Page_Load event or wherever you want. All you need to do is set the values to parameters and give a simple call to the required overload type of ExportDetails method.

    The following is the code block that demonstrates "exporting specified columns" of a DataTable as an Excel file from WebForm.

    Collapse
    [Code Behind]

    private void btnExport2_Click(object sender, System.EventArgs e)
    {
    // Export the details of specified columns

    try
    {
    // Get the datatable to export

    DataTable dtEmployee = ((DataSet)
    Session["dsEmployee"]).Tables["Employee"].Copy();

    // Specify the column list to export

    int[] iColumns = {1,2,3,5,6};

    // Export the details of specified columns to Excel

    RKLib.ExportData.Export objExport = new
    RKLib.ExportData.Export("Web");
    objExport.ExportDetails(dtEmployee,
    iColumns, Export.ExportFormat.Excel, "EmployeesInfo2.xls");
    }
    catch(Exception Ex)
    {
    lblError.Text = Ex.Message;
    }
    }

    The following is the code block that demonstrates "exporting specified columns" of a DataTable as a CSV file from WindowsForm.

    Collapse
    private void btnExportCSV_Click(object sender, System.EventArgs e)
    {
    // Export the details of specified columns

    try
    {
    lblMessage.Text = "";

    // Get the datatable to export

    DataTable dtEmployee = dsEmployee.Tables["Employee"].Copy();

    // Specify the column list to export

    int[] iColumns = {1,2,3,5,6};

    // Export the details of specified columns to CSV

    RKLib.ExportData.Export objExport = new
    RKLib.ExportData.Export("Win");
    objExport.ExportDetails(dtEmployee,
    iColumns, Export.ExportFormat.CSV,
    "C:\\EmployeesInfo.csv");
    lblMessage.Text = "Successfully exported to
    C:\\EmployeesInfo.csv"
    ;
    }
    catch(Exception Ex)
    {
    lblMessage.Text = Ex.Message;
    }
    }

    try this code to export data to csv file  try this code to export data to csv file

    24-Oct-08 09:51 AM
    private void OnExportGridToCSV(object sender, System.EventArgs e)
    {
    // Create the CSV file to which grid data will be exported.
    StreamWriter sw = new StreamWriter(Server.MapPath("~/GridData.txt"), false);
    // First we will write the headers.
    DataTable dt = m_dsProducts.Tables[0];
    int iColCount = dt.Columns.Count;
    for(int i = 0; i < iColCount; i++)
    {
    sw.Write(dt.Columns[i]);
    if (i < iColCount - 1)
    {
    sw.Write(",");
    }
    }
    sw.Write(sw.NewLine);
    // Now write all the rows.
    foreach (DataRow dr in dt.Rows)
    {
    for (int i = 0; i < iColCount; i++)
    {
    if (!Convert.IsDBNull(dr[i]))
    {
    sw.Write(dr[i].ToString());
    }
    if ( i < iColCount - 1)
    {
    sw.Write(",");
    }
    }
    sw.Write(sw.NewLine);
    }
    sw.Close();
    }
    read this code  read this code
    24-Oct-08 09:53 AM
    Snippets Code
    CSVHelper.cs
    /// <summary>
    /// Export Helper Function - DataGrid to CSV
    /// Converted from this article 
    /// http://www.dotnetbips.com/386541cb-7e0f-491f-b86a-f9bc8be738b8.aspx?articleid=302
    /// </summary>
    /// <param name="ds"></param>
    /// <param name="exportColumnHeadings"></param>
    /// <returns></returns>
    public string Export(DataSet ds, bool exportColumnHeadings)
    {
    string header = string.Empty;
    string body = string.Empty;
    string record = string.Empty;
    // If you want column to be part of the CSV ...
    if (exportColumnHeadings)
    {
    foreach (DataColumn col in ds.Tables[0].Columns)
    {
    header = header + (char)34 + col.ColumnName + (char)34 + ",";
    }
    header = header.Substring(0, header.Length - 1);
    }
    // Iterate into the rows
    foreach (DataRow row in ds.Tables[0].Rows)
    {
    Object[] arr = row.ItemArray;
    for (int i = 0; i < arr.Length - 1; i++)
    {
    if (arr[i].ToString().IndexOf(",") > 0)
    {
    record = record + (char)34 + arr[i].ToString() + (char)34 + ",";
    }
    else
    {
    record = record + arr[i].ToString() + ",";
    }
    }
    body = body + record.Substring(0, record.Length - 1) + Environment.NewLine;
    record = "";
    }
    if (exportColumnHeadings)
    {
    return (header + Environment.NewLine + body);
    }
    else
    {
    return body;
    }
    }
    Export.aspx.cs
    private void Page_Load(object sender, System.EventArgs e)
    {
    // Put user code to initialize the page here
    if (!IsPostBack)
    {
    BindGrid();
    }
    }
     
    // Retrieve the customer information and bind into the datagrid
    void BindGrid()
    {
    SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM Customers", "data source=wenching;initial catalog=northwind;user id=sa; password=Passw0rd");
    DataSet ds = new DataSet();
    da.Fill(ds, "customers");
    Session["myds"] = ds;
    dgResults.DataSource = ds;
    dgResults.DataBind();
    }
     
    private void btnExport_Click(object sender, System.EventArgs e)
    {
    DataSet ds = (DataSet)Session["myds"];
    CSVHelper csv = new CSVHelper();
    string strData = csv.Export(ds, chbExport.Checked);
    byte[] data = ASCIIEncoding.ASCII.GetBytes(strData);
    Response.Clear();
    // Set as Excel as the primary format
    Response.AddHeader("Content-Type", "application/Excel");
    // Save the output as customer.csv
    Response.AddHeader("Content-Disposition", "inline;filename=customer.csv");
    Response.BinaryWrite(data);
    Response.End();
    }
    try this code  try this code
    24-Oct-08 09:54 AM
    Private Sub Page_Load(ByVal sender As System.Object,_
    ByVal e As System.EventArgs) Handles MyBase.Load
    Dim ds as dataset=filldataset()
    dgBooks.DataSource = ds.Tables("Books")
    dgBooks.DataBind()

    'Set Export button properties
    btnExcel.Dataview = ds.Tables("Books").DefaultView
    btnExcel.FileNameToExport = "Books.xls"
    btnExcel.ExportType = _
    PNayak.Web.UI.WebControls.ExportButton.ExportTypeEnum.Excel
    btnExcel.Separator = _
    PNayak.Web.UI.WebControls.ExportButton.SeparatorTypeEnum.TAB

    End Sub
    small change  small change
    24-Oct-08 11:08 AM
    I suppose the only change required is "application/vnd.ms-excel"; instead of "Application/x-msexcel" which you specified for Content Type.... Ie, Response.Clear(); Response.AddHeader("Content-Type", "application/vnd.ms-excel"); Response.AddHeader("Content-Disposition", "attachment;filename=PrintCSV.csv"); Response.BinaryWrite(data); Response.End(); Response.Close();
    Create New Account
    help
    Interview Questions for .NET Framework This article is specially for the users those are in development or want to be a .net developer • To test a Web Service you must create a windows application or web application to consume this service? It is True / False? FALSE How many classes can a single.NET DLL contain? Answer1: As many Answer2: One or more What are good ADO.NET object(s) to replace the ADO Recordset object? The differences includes In ADO, the in memory representation of data is the recordset. In ADO.net, it is the dataset A recordset looks like a single table in ADO In contrast, a dataset is a collection of one or more tables in ADO.net ADO is designed primarily for connected access ADO net the disconnected access to the database is used In ADO you communicate with the database by making calls to an OLE DB provider. In ADO.NET you communicate with the database through a data adapter (an OleDbDataAdapter, SqlDataAdapter, OdbcDataAdapter, or OracleDataAdapter
    Frequently asked Interview Questions in ADO.Net hi friends Any one send frequently asked Important questions in C# .Net, ADO .Net, Asp .Net and Sql Server. . . . . . . . tx in Advance. . . . . . Hi, Find this. . (B)What is an IL? (B B) What is concept of Boxing and Unboxing ? (B) What is the difference between VB.NET and C#? (I) what is the difference between System exceptions and Application exceptions? (I)What is CODE Access security? (I)What is a satellite assembly? (A) How to prevent my .NET DLL to be decompiled? (I) what is the difference between Convert.toString and .toString () method assembly in GAC how do we make a choice? (A)What is CodeDom? Chapter 2: NET Interoperability (I) How can we use COM Components in .NET? (I) We have developed the COM wrapper do we have to still register the COM
    faqs on masterpages Hi all, can anybody tell me the FAQs on Masterpages in asp.net. Thanks alot var Hi What are Master Pages in ASP.NET? or What is a Master Page? ASP.NET master pages allow you to create a consistent layout for the pages in your application A single master page defines the look and feel and standard behavior that you want for all of the you want to display. When users request the content pages, they merge with the master page to produce output that combines the layout of the master page with the content from the content page. What are the 2 important parts of a master page? The following are the 2
    visual studio installation problem Actually, my OS is Windows Xp with service pack2.I added service pack3 to install visual studio2010.after that i tryed to installed, but am getting SETUP FAILED due to "Windows XP is not installed. [08 / 10 / 11, 14:26:00] VS70pgui: [2] DepCheck indicates Microsoft Visual F# 2.0 Runtime was not attempted to be installed. [08 / 10 / 11, 14:26:00] VS70pgui: [2] DepCheck indicates Microsoft Visual Studio Macro Tools was not attempted to be installed. [08 / 10 / 11, 14:26:00] VS70pgui not attempted to be installed. [08 / 10 / 11, 14:26:00] VS70pgui: [2] DepCheck indicates .NET Framework 4 Multi-Targeting Pack was not attempted to be installed. [08 / 10 / 11, 14:26:01] VS70pgui: [2] DepCheck indicates Microsoft Visual Studio 2010 Professional - ENU was not attempted to be installed. [08 / 10 / 11, 14:26
    e63e-4ee9-b396-3fc61e3e6b80 11 / 13 / 2011 00:08:31.87 w3wp.exe (0x0DB4) 0x0AB8 Excel Services Application Excel Calculation Services 8jg2 Medium ResourceManager.PerformCleanup: Memory Manager: CurrentSize = 536850432. 53fed7f1-b549-1a88-0000-000050f7b00c b289-46d6-9f02-ade97cfcf496 11 / 13 / 2011 00:08:34.05 w3wp.exe (0x0DB4) 0x0BEC Excel Services Application Excel Calculation Services 8jg2 Medium ResourceManager.PerformCleanup: Disk Manager: CurrentSize = 352934. 11c5f189-b549-1a88-0000-000050f7b00c 9ac7-45b9-a19e-ce6cc85ad1b9 11 / 13 / 2011 00:08:36.88 w3wp.exe (0x0DB4) 0x0AB8 Excel Services Application Excel Calculation Services 8jg2 Medium ResourceManager.PerformCleanup: Memory Manager: CurrentSize = 536850432. 53fed7f1-b549-1a88-0000-000050f7b00c 11 / 13 / 2011 00:08:41.88 w3wp.exe (0x0DB4) 0x0AB8 Excel Services Application Excel Calculation Services 8jg2 Medium ResourceManager.PerformCleanup: Memory Manager: CurrentSize = 536850432. 53fed7f1-b549-1a88-0000-000050f7b00c