Monday, February 17, 2014

Create CSV file from Data Table in asp.net with c#

Step 1:  Write this code on Button click event   


        if (GridLoginStatus.Rows.Count != 0)
        {
          string strFilePath =
            ConfigurationManager.AppSettings["CSVFilePath"];   
            CreateCSVFile(dt, strFilePath);
            lblErrorMsg.Text = "Report Saved";
        }
        else
        {
            lblErrorMsg.Text = "No Data Captured";

        }




Step 2:  Add a function on the form


    public void CreateCSVFile(DataTable dt, string strFilePath)
    {
        // Create the CSV file to which grid data will be exported.
        StreamWriter sw = new StreamWriter(strFilePath, false);
        // First we will write the headers.

        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();
    }

3 comments:

Generate All Database Backup From Sql Server Using Query

DECLARE   @name   VARCHAR ( 50 )   -- database name DECLARE   @path   VARCHAR ( 256 )   -- path for backup files DECLARE   @fileName  ...