方法一:
调用方法:StringToCSV(DtToString(你的DataTable),"pd","派单");
/// <summary> /// 将DataTable转换为字符串 /// </summary> /// <param name="dt"></param> /// <returns></returns> public static string DtToString(DataTable dt) { string data = ""; try { foreach (DataColumn column in dt.Columns) { data += column.ColumnName + ","; } data += "\r\n";//写出数据 foreach (DaTarow row in dt.Rows) { foreach (DataColumn column in dt.Columns) { string t = row[column].ToString(); if (!string.IsNullOrEmpty(t)) { t = t.Replace(",",""); t = t.Replace("\r",""); t = t.Replace("\n",""); t = HttpContext.Current.Server.HtmlEncode(t); data += t + ","; } else data += ","; } data += "\r\n"; } data += "\r\n"; } catch { } return data; } /// <summary> /// 将字符串转换为CSV格式输出 /// </summary> /// <param name="content">字符串内容</param> /// <param name="fileName">文件名(无扩展名)</param> /// <param name="msg">表头消息</param> public static void StringToCSV(string content,string fileName,string msg) { try { string temp = string.Format("attachment;filename={0}.csv",fileName); HttpContext.Current.Response.ClearHeaders(); HttpContext.Current.Response.Clear(); HttpContext.Current.Response.Buffer = true; HttpContext.Current.Response.Charset = "UTF-8"; HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.Default; HttpContext.Current.Response.ContentType = "application/ms-excel"; HttpContext.Current.Response.AppendHeader("Content-disposition",temp); if (!string.IsNullOrEmpty(msg)) HttpContext.Current.Response.Write(msg + "\r\n"); HttpContext.Current.Response.Write(content); HttpContext.Current.Response.End(); } catch { } }
方法二:在sql数据库 将字段中的逗号换成分号, 将回车或换行换成分号,组装字符串。
在sql数据库 将字段中的逗号换成分号, 将回车或换行换成分号,组装字符串。
格式如下:
a,b,c
d,e,f
g,h,j
保存为.csv文件
推荐阅读:
【推荐】.NET使用NPOI组件将数据导出Excel
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。