xiaofeng.NET系列之 netcore c#快速导出数据CSV格式 winfrom wpf
一个导出button
nuget 搜索
using XiaoFeng.IO;
using XiaoFeng;
private void button1_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(100000).ToList(); var csv = new CsvStreamWriter(path, false, Encoding.UTF8); Dictionary<string, string> dic = new Dictionary<string, string>() { { "ID","主键编码" }, { "DeviceId","设备编码" }, { "Name","名称" }, { "InspectionQuantity","检测数量" }, { "NumberOfAlarms","告警数量" }, { "PlayUrl","播放地址" }, { "Remark","备注" }, { "CreateTime","创建时间" }, }; var lists = new List<List<string>>(); var l = new List<string>();
//DeviceInfoModel 是实体类 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<string>(); 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("导出成功!"); } }
相信自己,一切皆有可能!