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

来源:互联网 发布:淘宝退货保留证据 编辑:程序博客网 时间:2024/04/30 09:32

功能说明:实现将数据装换为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);
        }


PS:最后是直接打开,能不能直接保存?

你的参数savePath那里用到了  你的那个方法GetTempPath在那里?

你添加上命名空间引用。using System.IO;我已经修改了


0 0