locked
data table to .CSV file RRS feed

Answers

  • User-1897546412 posted

    This is my code :

    protected void Button2_Click(object sender, EventArgs e)
    {
    string strConn = ConfigurationManager.ConnectionStrings["conString"].ToString();
    SqlConnection conn = new SqlConnection(strConn);
    SqlDataAdapter da = new SqlDataAdapter("select * from profile inner join Membership on Membership.MembershipID=Membership.ProfileID", conn);

    DataSet ds = new DataSet();

    da.Fill(ds, "Emp");
    DataTable dt = ds.Tables["Emp"];

    CreateCSVFile(dt, "E:\\Copy of insure\\csvData.csv");


    }
    public void CreateCSVFile(DataTable dt, string strFilePath)
    {

    #region Export to CSV

    // Create the CSV file .

    StreamWriter sw = new StreamWriter(strFilePath, 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();

    #endregion

    }

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, April 4, 2012 4:40 AM