C#Winform 实现数据的导出为txt或者CSV或者excel

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/pp_fzp/article/details/50709337
 //filePath 为保存到本地磁盘的位置
 private void Export(string filePath)   
        {
            using (FileStream fs=new FileStream(filePath,FileMode.Create,FileAccess.Write))
            {
                StreamWriter sw = new StreamWriter(fs);

                string col_txt = "";
                string row_txt = "";

                foreach (DataColumn item in dt.Columns)// dt为DataTable
                {
                    col_txt += item.ToString() + ","; // 循环得到列名
                }
                col_txt = col_txt.Substring(0, col_txt.Length - 1);
                sw.WriteLine(col_txt);  <span style="white-space:pre">//写入文件

                foreach (DataRow item in dt.Rows)  
                {
                    row_txt = "";  <span style="white-space:pre">//此处容易遗漏,导致数据的重复添加
                    for (int i = 0; i < dt.Columns.Count; i++)  
                    {
                        row_txt += item[i].ToString() + ","; //循环得到行数据
                    }
                    row_txt = row_txt.Substring(0, row_txt.Length - 1);
                    sw.WriteLine(row_txt);//写入文件
                }
                sw.Flush();   <span style="white-space:pre">//提交所进行的操作
            }
        }

猜你喜欢

转载自blog.csdn.net/pp_fzp/article/details/50709337