首页 > 代码库 > C# 导出csv格式的报表
C# 导出csv格式的报表
/// <summary> /// 导出报表为Csv /// </summary> /// <param name="dt">DataTable</param> /// <param name="strFilePath">物理路径</param> /// <param name="tableheader">表头</param> /// <param name="columname">字段标题,逗号分隔</param> public static bool dt2csv(DataTable dt, string strFilePath, string tableheader, string columname) { try { string strBufferLine = ""; StreamWriter strmWriterObj = new StreamWriter(strFilePath, false, System.Text.Encoding.UTF8); strmWriterObj.WriteLine(tableheader); strmWriterObj.WriteLine(columname); for (int i = 0; i < dt.Rows.Count; i++) { strBufferLine = ""; for (int j = 0; j < dt.Columns.Count; j++) { if (j > 0) strBufferLine += ","; strBufferLine += dt.Rows[i][j].ToString(); } strmWriterObj.WriteLine(strBufferLine); } strmWriterObj.Close(); return true; } catch { return false; } }
大家可能会用到List转DataTable的方法,附上:
/// <summary> /// List转DataTable /// </summary> /// <typeparam name="T"></typeparam> /// <param name="collection"></param> /// <returns></returns> public static DataTable ToDataTable<T>(IEnumerable<T> collection) { var props = typeof(T).GetProperties(); var dt = new DataTable(); dt.Columns.AddRange(props.Select(p => new DataColumn(p.Name, p.PropertyType)).ToArray()); if (collection.Count() > 0) { for (int i = 0; i < collection.Count(); i++) { ArrayList tempList = new ArrayList(); foreach (PropertyInfo pi in props) { object obj = pi.GetValue(collection.ElementAt(i), null); tempList.Add(obj); } object[] array = tempList.ToArray(); dt.LoadDataRow(array, true); } } return dt; }
调用的代码:
string file_path = AppDomain.CurrentDomain.BaseDirectory + @"\" + Guid.NewGuid().ToString() + ".csv"; DataTable dt = ToDataTable<Enterprise>(LIST_ENTERPRISE); if (dt2csv(dt, file_path, "企业信息", "注册号,公司名称,注册日期,插入时间")) { MessageBox.Show("导出成功,文件位置:" + file_path); } else { MessageBox.Show("导出失败,未知错误"); }
C# 导出csv格式的报表
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。