C#中將DataTable中資料匯出到csv檔案中

來源:互聯網
上載者:User

在上一篇博文【C#讀取CSV檔案的方法】中,我介紹了讀取csv檔案中資料的方法,現在我來介紹下將datatable中的資料匯出到csv檔案中的方法,廢話不

多說了,deme程式的代碼如下:

 protected void Button1_Click(object sender, EventArgs e)
    {
        DataTable dt = new DataTable();
        dt.Columns.Add("test1");
        dt.Columns.Add("test2");
        dt.Columns.Add("test3");
        dt.Columns.Add("test4");
        dt.Columns.Add("test5");
        for (int i = 0; i < 6; i++)
        {
            dt.Rows.Add();
            dt.Rows[i][0] = "CN"+i.ToString();
            dt.Rows[i][1] = "EN"+i.ToString();
            dt.Rows[i][2] = "JN"+i.ToString();
            dt.Rows[i][3] = "HK"+i.ToString();
            dt.Rows[i][4] = "TW"+i.ToString();
        }

        ExportDataGridToCSV(dt);

    }

    /// <summary>
    /// Export the data from datatable to CSV file
    /// </summary>
    /// <param name="grid"></param>
    public void ExportDataGridToCSV(DataTable dt)
    {
        string strFile = "";
        string path = "";
        
        //File info initialization
        strFile = "test";
        strFile = strFile + DateTime.Now.ToString("yyyyMMddhhmmss");
        strFile = strFile + ".csv";
        path = Server.MapPath(strFile);

        

        System.IO.FileStream fs = new FileStream(path, System.IO.FileMode.Create, System.IO.FileAccess.Write);
        StreamWriter sw = new StreamWriter(fs, new System.Text.UnicodeEncoding());
        //Tabel header
        for (int i = 0; i < dt.Columns.Count; i++)
        {
            sw.Write(dt.Columns[i].ColumnName);
            sw.Write("\t");
        }
        sw.WriteLine("");
        //Table body
        for (int i = 0; i < dt.Rows.Count; i++)
        {
            for (int j = 0; j < dt.Columns.Count; j++)
            {
                sw.Write(DelQuota(dt.Rows[i][j].ToString()));
                sw.Write("\t");
            }
            sw.WriteLine("");
        }
        sw.Flush();
        sw.Close();

        DownLoadFile(path);
    }

    private bool DownLoadFile(string _FileName)
    {
        try
        {
            System.IO.FileStream fs = System.IO.File.OpenRead(_FileName);
            byte[] FileData = new byte[fs.Length];
            fs.Read(FileData, 0, (int)fs.Length);
            Response.Clear();
            Response.AddHeader("Content-Type", "application/notepad");
            string FileName = System.Web.HttpUtility.UrlEncode(System.Text.Encoding.UTF8.GetBytes(_FileName));
            Response.AddHeader("Content-Disposition", "inline;filename=" + System.Convert.ToChar(34) + FileName + System.Convert.ToChar(34));
            Response.AddHeader("Content-Length", fs.Length.ToString());
            Response.BinaryWrite(FileData);
            fs.Close();
            System.IO.File.Delete(_FileName);
            Response.Flush();
            Response.End();
            return true;
        }
        catch (Exception ex)
        {
            ex.Message.ToString();
            return false;
        }
    }

    /// <summary>
    /// Delete special symbol
    /// </summary>
    /// <param name="str"></param>
    /// <returns></returns>
    public string DelQuota(string str)
    {
        string result = str;
        string[] strQuota ={ "~", "!", "@", "#", "$", "%", "^", "&", "*", "(", ")", "`", ";", "'", ",", ".", "/", ":", "/,", "<", ">", "?" };
        for (int i = 0; i < strQuota.Length; i++)
        {
            if (result.IndexOf(strQuota[i]) > -1)
                result = result.Replace(strQuota[i], "");
        }
        return result;
    }

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.