C#开发小试手----小功能:csv文件保存

本文详细介绍了一种从DataGridView导出数据至CSV文件的方法,包括创建表头、保存表格数据及通过对话框选择保存路径。文章提供了具体代码实现,涵盖表头定义、数据写入逻辑及异常处理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

需求:将页面dataGridView里的表格存入本地csv文件

本例的dataGridView里的数据由于已经存在DataTable中,故直接出用即可。

1.创建表头

由于DataTable,未将表头存入,故在此进行表头的定义。

     public void CreateCSV_Head(string CSV_Head, string fullPath)
        {  //定义csv表格的表头
            System.IO.FileInfo fi = new System.IO.FileInfo(fullPath);
            if (!fi.Directory.Exists)
            {
                fi.Directory.Create();
            }
            System.IO.FileStream fs = new System.IO.FileStream(fullPath, System.IO.FileMode.Append,
            System.IO.FileAccess.Write);
            System.IO.StreamWriter sw = new System.IO.StreamWriter(fs, System.Text.Encoding.Default);
            sw.WriteLine(CSV_Head);
            sw.Close();
            fs.Close();
        }

2.保存表格 

文件流的System.IO.FileMode.Append属性表示文件读写的追加

         public void SaveCSV(DataTable dt, string fullPath)//FTA数据写入csv
        {
            System.IO.FileInfo fi = new System.IO.FileInfo(fullPath);
            if (!fi.Directory.Exists)
            {
                fi.Directory.Create();
            }
            System.IO.FileStream fs = new System.IO.FileStream(fullPath, System.IO.FileMode.Append,
            System.IO.FileAccess.Write);
            System.IO.StreamWriter sw = new System.IO.StreamWriter(fs, System.Text.Encoding.Default);
            //定义csv表格的前两个字段

            for (int i = 0; i < dt.Rows.Count; i++)
            {
                string data = "";
                for (int j = 0; j < dt.Columns.Count; j++)
                {
                    string str = dt.Rows[i][j].ToString();
                    Console.Write(str);
                    str = str.Replace("\"", "\"\"");//替换英文冒号 英文冒号需要换成两个冒号
                    if (str.Contains(',') || str.Contains('"')
                        || str.Contains('\r') || str.Contains('\n')) //含逗号 冒号 换行符的需要放到引号中
                    {
                        str = string.Format("\"{0}\"", str);
                    }

                    data += str;
                    if (j < dt.Columns.Count - 1)
                    {
                        data += ",";
                    }
                }
                sw.WriteLine(data);
            }
            sw.Close();
            fs.Close();
        }

       

3.实现通过对话框保存

通过Dialog实现保存对话框,并返回文件的全路径,传给SaveCSV方法和CreateCSV_Head方法,实现保存

        private void button8_Click_1(object sender, EventArgs e)
        {
            if (dt.Columns.Count != 6)
            {
                MessageBox.Show("请完成计算后再进行保存");
            }

            else
            {
                //打开保存文件的对话框
                SaveFileDialog sfd = new SaveFileDialog();
                sfd.Title = "";
                sfd.InitialDirectory = @"C:\";
                sfd.Filter = "逗号分隔符| *.csv";
                sfd.ShowDialog();
                //返回文件全路径
                string path = sfd.FileName;
                if (path == "")
                {
                    return;
                }

                string CSV_Head = "字段1,字段2,字段3,字段4,字段5,字段6";//定义表头字段

                if (!File.Exists(path))
                {
                    CreateCSV_Head(CSV_Head, path);//如果不存在,创建csv文件,并创建表头
                }
                try
                {//防止csv文件被占用的异常
                    SaveCSV(dt, path); ;//该算法所有历史结果存储,存在Debug下
                }
                catch (IOException index0)
                {
                    MessageBox.Show("保存文件出错:" + index0.Message + "请关闭该文件后再执行保存!");
                }
            }

        }

4.总结

此方法可以实现文件保存,但是创建表头和写入其余内容分开写不太合理,待有空改进

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值