导出CSV数据格式用法
作者 : Jacky 发布于 2023-05-23 16:23:33 浏览 888 次
演示了在winfrom wpf 中如何快速导出csv格式数据

第一步安装xiaofeng nugte包。
然后在你的界面引用
using XiaoFeng.IO;
using XiaoFeng;
做一个按钮控件:

 private async void btnExportCSV_Click(object sender, EventArgs e)
        {
            var savedlg = new FolderBrowserDialog()
            {
                Description = "选择保存的路径",
                UseDescriptionForTitle = true,
                RootFolder = Environment.SpecialFolder.Desktop,
                ShowNewFolderButton = true
            };
            if (savedlg.ShowDialog() == DialogResult.OK)
            {

                var path = savedlg.SelectedPath + "\\" + DateTime.Now.ToString("yyyyMMddHHmmssfffffff") + ".csv";
                var list = DeviceInfoModel.Create.QueryableX.Take(1000).ToList();

                var csv = new CsvStreamWriter(path, false, Encoding.UTF8);
                Dictionary dic = new Dictionary()
                {
                   { "ID","主键编码" },
                   { "DeviceId","设备编码" },
                   { "Name","名称" },
                   { "InspectionQuantity","检测数量" },
                   { "NumberOfAlarms","告警数量" },
                   { "PlayUrl","播放地址" },
                   { "Remark","备注" },
                   { "CreateTime","创建时间" },
                };

                var lists = new List>();
                var l = new List();
                typeof(DeviceInfoModel).GetProperties(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.IgnoreCase).Each(a =>
                {
                    if (!dic.Keys.Contains(a.Name, StringComparer.OrdinalIgnoreCase)) return;
                    //l.Add(a.GetDescription());  读书字段属性的描述文本
                    l.Add(dic[a.Name]);
                });

                lists.Add(l);
                list.Each(a =>
                {
                    var l = new List();
                    a.AllKeys.Each(b =>
                    {
                        if (!dic.Keys.Contains(b, StringComparer.OrdinalIgnoreCase)) return;

                        var val = a[b];
                        if (val is DateTime dt)
                            val = "'" + dt.ToString("yyyy-MM-dd HH:mm:ss");
                        l.Add(val.ToString());
                    });
                    lists.Add(l);
                });

                csv.Write(lists);
                csv.Close();
                csv.Dispose();
                MessageBox.Show("导出成功!");

            }

        }

以上就是导出csv的基本用法了。
注释:DeviceInfoModel 是一个实体类。

如果数据的格式不是你想要的,可以修改格式

if (val is DateTime dt)
{
   val = "'" + dt.ToString("yyyy-MM-dd HH:mm:ss");
}
所有评论(0)