生成CSV文件

        /// <summary>
        /// 写入CSV文件
        /// </summary>
        /// <param name="path">文件路径</param>
        /// <param name="dt">数据源</param>
        private void writeCsv(string path, DataTable dt)
        {
            using (StreamWriter sw = new StreamWriter(path, false, Encoding.Default))
            {
                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(Environment.NewLine);
                foreach (DataRow dr in dt.Rows)
                {
                    for (int i = 0; i < iColCount; i++)
                    {
                        if (!Convert.IsDBNull(dr[i]))
                        {
                            sw.Write("\"" + dr[i].ToString().Replace("\"", "\"\"") + "\"");
                        }
                        if (i < iColCount - 1)
                        {
                            sw.Write(",");
                        }
                    }
                    sw.Write(Environment.NewLine);
                }
            }

            //判断文件是否生成成功
            while (!File.Exists(path))
            {
                System.Threading.Thread.Sleep(1000);
            }
        }
posted @ 2012-04-23 16:00    阅读(693)  评论(0编辑  收藏  举报