您的位置:首页 > 编程语言 > C#

C#中将DataTable中数据导出到csv文件中

2016-01-29 10:45 906 查看



功能说明:实现将数据装换为csv格式,数据来源可以是任意的,先把数据保存到Datatable中,再转换为csv文件即可。    
  方法一:将内存 DataTable中数据保存到csv文件中
 using System.Text;

using System.IO;

using System.Data;
       /// <summary>

        /// 将datatable中的数据保存到csv中

        /// </summary>

        /// <param name="dt">数据来源</param>

        /// <param name="savaPath">保存的路径</param>

        /// <param name="strName">保存文件的名称</param>

        public void ExportToSvc(System.Data.DataTable dt,string savaPath, string strName)

        {

             string strPath = Path.GetTempPath() + strName + ".csv";//保存到本项目文件夹下
            //string strPath = savaPath + "\\" + strName + ".csv";//保存到指定目录下
            if (File.Exists(strPath))

            {

                File.Delete(strPath);

            }

            //先打印标头

            StringBuilder strColu = new StringBuilder();

            StringBuilder strValue = new StringBuilder();

            int i = 0;

            try

            {

                StreamWriter sw = new StreamWriter(new FileStream(strPath, FileMode.CreateNew), Encoding.GetEncoding("GB2312"));

                for (i = 0; i <= dt.Columns.Count - 1; i++)

                {

                    strColu.Append(dt.Columns[i].ColumnName);

                    strColu.Append(",");

                }

                strColu.Remove(strColu.Length - 1, 1);//移出掉最后一个,字符

                sw.WriteLine(strColu);

                foreach (DataRow dr in dt.Rows)

                {

                    strValue.Remove(0, strValue.Length);//移出

                    for (i = 0; i <= dt.Columns.Count - 1; i++)

                    {

                        strValue.Append(dr[i].ToString());

                        strValue.Append(",");

                    }

                    strValue.Remove(strValue.Length - 1, 1);//移出掉最后一个,字符

                    sw.WriteLine(strValue);

                }

                sw.Close();

            }

            catch (Exception ex)

            {

                MessageBox.Show(ex.Message);

            }

            System.Diagnostics.Process.Start(strPath);

        }
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: