C#导出CSV文件

  public static void TableToCsv(DataTable dt,string filePath)
        {
            FileInfo fi = new FileInfo(filePath);
            string path = fi.DirectoryName;
            string name = fi.Name;
            //\/:*?"<>|
            //把文件名和路径分别取出来处理
            name = name.Replace(@"\", "\");
            name = name.Replace(@"/", "/");
            name = name.Replace(@":", ":");
            name = name.Replace(@"*", "*");
            name = name.Replace(@"?", "?");
            name = name.Replace(@"<", "<");
            name = name.Replace(@">", ">");
            name = name.Replace(@"|", "|");
            string title = "";

            FileStream fs = new FileStream(path + "\\" + name, FileMode.Create);
            StreamWriter sw = new StreamWriter(new BufferedStream(fs), System.Text.Encoding.Default);

            for (int i = 0; i < dt.Columns.Count; i++)
            {
                title += dt.Columns[i].ColumnName + ",";
            }
            title = title.Substring(0, title.Length - 1) + "\n";
            sw.Write(title);

            foreach (DataRow row in dt.Rows)
            {
                if (row.RowState == DataRowState.Deleted) continue;
                string line = "";
                for (int i = 0; i < dt.Columns.Count; i++)
                {
                    line += row[i].ToString().Replace(",", "") + ",";
                }
                line = line.Substring(0, line.Length - 1) + "\n";

                sw.Write(line);
            }

            sw.Close();
            fs.Close();
        }

你可能感兴趣的:(.Net)