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"); }
3、编写Excel的数据行,该部分的功能主要是将数据源里的数据,写入到Excel中。foreach (TB忧溲枷茫_StandardArea t in lt) { for (i = 0, j = myPropertyInfo.Length; i < j; i++) { System.Reflection.PropertyInfo pi = myPropertyInfo[i]; string str = $"{pi.GetValue(t, null)}".Replace("\n", ""); if (str == "") { builder.Append("\t"); } else { builder.Append(str + "\t"); //横向跳到另一个单元格 } } builder.Append("\n"); //换行 }
4、添加cvs格式的文件生成,如果不存在则需要创建相应的目录,否则在写入时,有可能出现文件不存在的异常。string name = $"行政区划{rn.Next(9999)}.cvs"; string path = ($"{AppDomain.CurrentDomain.BaseDirectory}\\Document\\"); if (!Directory.Exists(path)) Directory.CreateDirectory(path);
5、将编写的Excel数据写入到添加csv文件中,将cvs打开,然后,通过文件写入方法,把数据写入进去即可。因为一般写入文件会出现意想不到的异常,这里最好加入异常获取,防止程序崩溃。try { dt = System.Text.Encoding.GetEncoding("GB2312").GetBytes(builder.ToString()); System.IO.FileStream fs = System.IO.File.OpenWrite(fileFullName); fs.Write(dt, 0, dt.Length); fs.Close(); System.Diagnostics.Process.Start(path); } catch (Exception ex) { Log.CreateLog(ex.Message); }