生成CSV文件

CSV(Comma-Separated Values,CSV,有时也称为字符分隔值,因为分隔字符也可以不是逗号)
CSV文件比较简单,导出表格时格式没有要求的可以导出CSV文件用excel打开

生成CSV文件代码。

namespace CreatCSVFile
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            List<int> ii = new List<int>() { 1, 2, 3, 4, 5, 6, 7 };
            ii.Sort((c1, c2) =>
            {
                if (c1 == 3)
                    return 1;
                return 0;
            });


            DataTable dt = new DataTable();
            dt.Columns.Add("name", Type.GetType("System.String"));
            dt.Columns.Add("sex", Type.GetType("System.String"));
            dt.Columns.Add("age", Type.GetType("System.Int32"));
            dt.Rows.Add("张三", "男", "22");
            dt.Rows.Add("李四", "男", "28");
            dt.Rows.Add("王二", "男", "30");

            string listSeparator = ";";
            string intervalchar = "";
            SaveFileDialog saveFileDialog = new SaveFileDialog();
            saveFileDialog.Title = "保存到CSV文件";
            saveFileDialog.Filter = "CSVFile(*.csv)|*.csv";
            if (saveFileDialog.ShowDialog() == DialogResult.OK)
            {
                string path = saveFileDialog.FileName;
                if (IsFileUsedByAnotherProcess(path))
                {
                    MessageBox.Show("文件被其他进程占用");
                    return;
                }
                if (File.Exists(path))
                {
                    File.Delete(path);
                }
                using (FileStream fs = new FileStream(path, FileMode.CreateNew, FileAccess.Write, FileShare.ReadWrite))//用FileShare.ReadWrite在其他进程占用时也可以读
                {
                    using (StreamWriter sw = new StreamWriter(fs, Encoding.UTF8))
                    {
                        sw.WriteLine("表格");
                        DataTableReader dr = dt.CreateDataReader();
                        while (dr.Read())
                        {
                            string str = "";
                            int len = dr.FieldCount;
                            int count = 0;
                            for (int i = 0; i < len; i++)
                            {
                                intervalchar = count++ == 0 ? "" : listSeparator;
                                str += intervalchar + dr.GetValue(i).ToString();
                            }
                            sw.WriteLine(str);
                        }
                    }
                }
        }}

        private bool IsFileUsedByAnotherProcess(string file)
        {
            try
            {
                if (File.Exists(file))
                {
                    using (FileStream fs = File.Open(file, FileMode.Open, FileAccess.Read, FileShare.None))
                    {
                        return false;
                    }
                }
                return false;
            }
            catch (Exception ex)
            {
                return true;
            }
        }
    }
}

要注意的是:分隔符不一定是”,”
系统的列表分隔符是可以在控制面板里设置的,文件内容中的分隔符与系统设置一致时Microsoft Excel才会分隔(系统设置好像对WPS Excel无效,一直都以,为分隔符)
这里写图片描述

也可以在Excel 数据=》分列 里设置分隔符使其正确显示,不过保存后用txt打开可以发现,这样设置本质是将文件内容里的分隔符给改成了系统设置的分隔符。
这里写图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值