C#如何导出csv格式
1、要导出数据,首先第一步就是要获取数据,将数据从数据库中抽离出来,然后将数据导出到csv中。因作者使用的是ef,故数据源的获取方式,本文不做讲解。

2、编写Excel的头部生成代码,即表格的表头。这里主要通过反射,将字段名写到表头上。System.Reflection.霸烹钟爷PropertyInfo[] myPropertyInfo = lt.First().GetType() .GetProperties(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance); int i = 0, j; for (i = 0, j = myPropertyInfo.Length; i < j; i++) { System.Reflection.PropertyInfo pi = myPropertyInfo[i]; string headname = pi.Name; //单元格头部 builder.Append(headname); builder.Append("\t"); }

4、添加cvs格式的文件生成,如果不存在则需要创建相应的目录,否则在写入时,有可能出现文件不存在的异常。string name = $"行政区划{rn.Next(9999)}.cvs"; string path = ($"{AppDomain.CurrentDomain.BaseDirectory}\\Document\\"); if (!Directory.Exists(path)) Directory.CreateDirectory(path);

