c# DataTable 导出csv文件
using System;
using System.Data;
using System.Configuration;
using System.Collections.Generic;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Text;
using System.Reflection;
using System.IO;
using System.Data.Odbc;
namespace HuaTong.General.Utility
{
public class CSVHelper
{
#region Fields
string _fileName;
DataTable _dataSource;//数据源
string[] _titles = null;//列标题
string[] _fields = null;//字段名 List<string> listTitles = new List<string>();
List<string> listFields = new List<string>();
#endregion
#region .ctor
/// <summary>
/// 构造函数
/// </summary>
/// <param name="dataSource">数据源</param>
public CSVHelper()
{
}
/// <summary>
/// 构造函数
/// </summary>
/// <param name="titles">要输出到 Excel 的列标题的数组</param>
/// <param name="fields">要输出到 Excel 的字段名称数组</param>
/// <param name="dataSource">数据源</param>
public CSVHelper(string[] titles, string[] fields, DataTable dataSource)
: this(titles, dataSource)
{
if (fields == null || fields.Length == )
throw new ArgumentNullException("fields");
if (titles.Length != fields.Length)
throw new ArgumentException("titles.Length != fields.Length", "fields");
_fields = fields;
} public CSVHelper(List<string> titles, List<string> fields, DataTable dataSource)
: this(titles,dataSource)
{
if (fields == null || fields.Count == )
throw new ArgumentNullException("fields");
if (titles.Count != fields.Count)
throw new ArgumentException("titles.Count != fields.Count", "fields");
listFields = fields;
}
/// <summary>
/// 构造函数
/// </summary>
/// <param name="titles">要输出到 Excel 的列标题的数组</param>
/// <param name="dataSource">数据源</param>
public CSVHelper(string[] titles, DataTable dataSource)
: this(dataSource)
{
if (titles == null || titles.Length == )
throw new ArgumentNullException("titles");
_titles = titles;
} public CSVHelper(List<string> titles, DataTable dataSource)
: this(dataSource)
{
if (titles == null || titles.Count == )
throw new ArgumentNullException("titles");
listTitles = titles;
}
/// <summary>
/// 构造函数
/// </summary>
/// <param name="dataSource">数据源</param>
public CSVHelper(DataTable dataSource)
{
if (dataSource == null)
throw new ArgumentNullException("dataSource");
// maybe more checks needed here (IEnumerable, IList, IListSource, ) ???
// 很难判断,先简单的使用 DataTable
_dataSource = dataSource;
}
#endregion
#region public Methods
#region 导出到CSV文件并且提示下载
/// <summary>
/// 导出到CSV文件并且提示下载
/// </summary>
/// <param name="fileName"></param>
public byte[] DataToCSV(string fileName)
{
string data = listTitles.Count > ? ExportCSVForActiveTitle():ExportCSV();
return System.Text.Encoding.Default.GetBytes(data);
/*HttpContext.Current.Response.ClearHeaders();
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.Expires = 0;
HttpContext.Current.Response.BufferOutput = true;
HttpContext.Current.Response.Charset = "GB2312";
HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
HttpContext.Current.Response.AppendHeader("Content-Disposition", string.Format("attachment;filename={0}.csv", System.Web.HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8)));
HttpContext.Current.Response.ContentType = "text/h323;charset=gbk";
HttpContext.Current.Response.Write(data);
HttpContext.Current.Response.End();*/
}
#endregion
/// <summary>
/// 获取CSV导入的数据
/// </summary>
/// <param name="filePath">文件路径</param>
/// <param name="fileName">文件名称(.csv不用加)</param>
/// <returns></returns>
public DataTable GetCsvData(string filePath, string fileName)
{
string path = Path.Combine(filePath, fileName + ".csv");
string connString = @"Driver={Microsoft Text Driver (*.txt; *.csv)};Dbq=" + filePath + ";Extensions=asc,csv,tab,txt;";
try
{
using (OdbcConnection odbcConn = new OdbcConnection(connString))
{
odbcConn.Open();
OdbcCommand oleComm = new OdbcCommand();
oleComm.Connection = odbcConn;
oleComm.CommandText = "select * from [" + fileName + "#csv]";
OdbcDataAdapter adapter = new OdbcDataAdapter(oleComm);
DataSet ds = new DataSet();
adapter.Fill(ds, fileName);
return ds.Tables[];
odbcConn.Close();
}
if (File.Exists(path))
{
File.Delete(path);
}
}
catch (Exception ex)
{
if (File.Exists(path))
{
File.Delete(path);
}
throw ex;
}
}
#endregion
#region 返回写入CSV的字符串
/// <summary>
/// 返回写入CSV的字符串
/// </summary>
/// <returns></returns>
private string ExportCSV()
{
if (_dataSource == null)
throw new ArgumentNullException("dataSource");
StringBuilder strbData = new StringBuilder();
if (_titles == null)
{
//添加列名
foreach (DataColumn column in _dataSource.Columns)
{
strbData.Append(column.ColumnName + ",");
}
strbData.Append("\n");
foreach (DataRow dr in _dataSource.Rows)
{
for (int i = ; i < _dataSource.Columns.Count; i++)
{
strbData.Append(dr[i].ToString() + ",");
}
strbData.Append("\n");
}
return strbData.ToString();
}
else
{
foreach (string columnName in _titles)
{
strbData.Append(columnName + ",");
}
strbData.Append("\n");
if (_fields == null)
{
foreach (DataRow dr in _dataSource.Rows)
{
for (int i = ; i < _dataSource.Columns.Count; i++)
{
strbData.Append(dr[i].ToString() + ",");
}
strbData.Append("\n");
}
return strbData.ToString();
}
else
{
foreach (DataRow dr in _dataSource.Rows)
{
for (int i = ; i < _fields.Length; i++)
{
strbData.Append(dr[_fields[i]].ToString() + ",");
}
strbData.Append("\n");
}
return strbData.ToString();
}
}
} private string ExportCSVForActiveTitle()
{
if (_dataSource == null)
throw new ArgumentNullException("dataSource");
StringBuilder strbData = new StringBuilder();
if (listTitles.Count == )
{
//添加列名
foreach (DataColumn column in _dataSource.Columns)
{
strbData.Append(column.ColumnName + ",");
}
strbData.Append("\n");
foreach (DataRow dr in _dataSource.Rows)
{
for (int i = ; i < _dataSource.Columns.Count; i++)
{
strbData.Append(dr[i].ToString() + ",");
}
strbData.Append("\n");
}
return strbData.ToString();
}
else
{
foreach (string columnName in listTitles)
{
strbData.Append(columnName + ",");
}
strbData.Append("\n");
if (listFields.Count == )
{
foreach (DataRow dr in _dataSource.Rows)
{
for (int i = ; i < _dataSource.Columns.Count; i++)
{
strbData.Append(dr[i].ToString() + ",");
}
strbData.Append("\n");
}
return strbData.ToString();
}
else
{
foreach (DataRow dr in _dataSource.Rows)
{
for (int i = ; i < listFields.Count; i++)
{
strbData.Append(dr[listFields[i]].ToString() + ",");
}
strbData.Append("\n");
}
return strbData.ToString();
}
}
}
#endregion
#region 得到一个随意的文件名
/// <summary>
/// 得到一个随意的文件名
/// </summary>
/// <returns></returns>
private string GetRandomFileName()
{
Random rnd = new Random((int)(DateTime.Now.Ticks));
string s = rnd.Next(Int32.MaxValue).ToString();
return DateTime.Now.ToShortDateString() + "_" + s + ".csv";
}
#endregion
}
}
using System;
using System.Data;
using System.Configuration;
using System.Collections.Generic;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Text;
using System.Reflection;
using System.IO;
using System.Data.Odbc;
namespace HuaTong.General.Utility
{
public class CSVHelper
{
#region Fields
string _fileName;
DataTable _dataSource;//数据源
string[] _titles = null;//列标题
string[] _fields = null;//字段名
List<string> listTitles = new List<string>();
List<string> listFields = new List<string>();
#endregion
#region .ctor
/// <summary>
/// 构造函数
/// </summary>
/// <param name="dataSource">数据源</param>
public CSVHelper()
{
}
/// <summary>
/// 构造函数
/// </summary>
/// <param name="titles">要输出到 Excel 的列标题的数组</param>
/// <param name="fields">要输出到 Excel 的字段名称数组</param>
/// <param name="dataSource">数据源</param>
public CSVHelper(string[] titles, string[] fields, DataTable dataSource)
: this(titles, dataSource)
{
if (fields == null || fields.Length == 0)
throw new ArgumentNullException("fields");
if (titles.Length != fields.Length)
throw new ArgumentException("titles.Length != fields.Length", "fields");
_fields = fields;
}
public CSVHelper(List<string> titles, List<string> fields, DataTable dataSource)
: this(titles,dataSource)
{
if (fields == null || fields.Count == 0)
throw new ArgumentNullException("fields");
if (titles.Count != fields.Count)
throw new ArgumentException("titles.Count != fields.Count", "fields");
listFields = fields;
}
/// <summary>
/// 构造函数
/// </summary>
/// <param name="titles">要输出到 Excel 的列标题的数组</param>
/// <param name="dataSource">数据源</param>
public CSVHelper(string[] titles, DataTable dataSource)
: this(dataSource)
{
if (titles == null || titles.Length == 0)
throw new ArgumentNullException("titles");
_titles = titles;
}
public CSVHelper(List<string> titles, DataTable dataSource)
: this(dataSource)
{
if (titles == null || titles.Count == 0)
throw new ArgumentNullException("titles");
listTitles = titles;
}
/// <summary>
/// 构造函数
/// </summary>
/// <param name="dataSource">数据源</param>
public CSVHelper(DataTable dataSource)
{
if (dataSource == null)
throw new ArgumentNullException("dataSource");
// maybe more checks needed here (IEnumerable, IList, IListSource, ) ???
// 很难判断,先简单的使用 DataTable
_dataSource = dataSource;
}
#endregion
#region public Methods
#region 导出到CSV文件并且提示下载
/// <summary>
/// 导出到CSV文件并且提示下载
/// </summary>
/// <param name="fileName"></param>
public byte[] DataToCSV(string fileName)
{
string data = listTitles.Count > 0 ? ExportCSVForActiveTitle():ExportCSV();
return System.Text.Encoding.Default.GetBytes(data);
/*HttpContext.Current.Response.ClearHeaders();
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.Expires = 0;
HttpContext.Current.Response.BufferOutput = true;
HttpContext.Current.Response.Charset = "GB2312";
HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
HttpContext.Current.Response.AppendHeader("Content-Disposition", string.Format("attachment;filename={0}.csv", System.Web.HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8)));
HttpContext.Current.Response.ContentType = "text/h323;charset=gbk";
HttpContext.Current.Response.Write(data);
HttpContext.Current.Response.End();*/
}
#endregion
/// <summary>
/// 获取CSV导入的数据
/// </summary>
/// <param name="filePath">文件路径</param>
/// <param name="fileName">文件名称(.csv不用加)</param>
/// <returns></returns>
public DataTable GetCsvData(string filePath, string fileName)
{
string path = Path.Combine(filePath, fileName + ".csv");
string connString = @"Driver={Microsoft Text Driver (*.txt; *.csv)};Dbq=" + filePath + ";Extensions=asc,csv,tab,txt;";
try
{
using (OdbcConnection odbcConn = new OdbcConnection(connString))
{
odbcConn.Open();
OdbcCommand oleComm = new OdbcCommand();
oleComm.Connection = odbcConn;
oleComm.CommandText = "select * from [" + fileName + "#csv]";
OdbcDataAdapter adapter = new OdbcDataAdapter(oleComm);
DataSet ds = new DataSet();
adapter.Fill(ds, fileName);
return ds.Tables[0];
odbcConn.Close();
}
if (File.Exists(path))
{
File.Delete(path);
}
}
catch (Exception ex)
{
if (File.Exists(path))
{
File.Delete(path);
}
throw ex;
}
}
#endregion
#region 返回写入CSV的字符串
/// <summary>
/// 返回写入CSV的字符串
/// </summary>
/// <returns></returns>
private string ExportCSV()
{
if (_dataSource == null)
throw new ArgumentNullException("dataSource");
StringBuilder strbData = new StringBuilder();
if (_titles == null)
{
//添加列名
foreach (DataColumn column in _dataSource.Columns)
{
strbData.Append(column.ColumnName + ",");
}
strbData.Append("\n");
foreach (DataRow dr in _dataSource.Rows)
{
for (int i = 0; i < _dataSource.Columns.Count; i++)
{
strbData.Append(dr[i].ToString() + ",");
}
strbData.Append("\n");
}
return strbData.ToString();
}
else
{
foreach (string columnName in _titles)
{
strbData.Append(columnName + ",");
}
strbData.Append("\n");
if (_fields == null)
{
foreach (DataRow dr in _dataSource.Rows)
{
for (int i = 0; i < _dataSource.Columns.Count; i++)
{
strbData.Append(dr[i].ToString() + ",");
}
strbData.Append("\n");
}
return strbData.ToString();
}
else
{
foreach (DataRow dr in _dataSource.Rows)
{
for (int i = 0; i < _fields.Length; i++)
{
strbData.Append(dr[_fields[i]].ToString() + ",");
}
strbData.Append("\n");
}
return strbData.ToString();
}
}
}
private string ExportCSVForActiveTitle()
{
if (_dataSource == null)
throw new ArgumentNullException("dataSource");
StringBuilder strbData = new StringBuilder();
if (listTitles.Count == 0)
{
//添加列名
foreach (DataColumn column in _dataSource.Columns)
{
strbData.Append(column.ColumnName + ",");
}
strbData.Append("\n");
foreach (DataRow dr in _dataSource.Rows)
{
for (int i = 0; i < _dataSource.Columns.Count; i++)
{
strbData.Append(dr[i].ToString() + ",");
}
strbData.Append("\n");
}
return strbData.ToString();
}
else
{
foreach (string columnName in listTitles)
{
strbData.Append(columnName + ",");
}
strbData.Append("\n");
if (listFields.Count == 0)
{
foreach (DataRow dr in _dataSource.Rows)
{
for (int i = 0; i < _dataSource.Columns.Count; i++)
{
strbData.Append(dr[i].ToString() + ",");
}
strbData.Append("\n");
}
return strbData.ToString();
}
else
{
foreach (DataRow dr in _dataSource.Rows)
{
for (int i = 0; i < listFields.Count; i++)
{
strbData.Append(dr[listFields[i]].ToString() + ",");
}
strbData.Append("\n");
}
return strbData.ToString();
}
}
}
#endregion
#region 得到一个随意的文件名
/// <summary>
/// 得到一个随意的文件名
/// </summary>
/// <returns></returns>
private string GetRandomFileName()
{
Random rnd = new Random((int)(DateTime.Now.Ticks));
string s = rnd.Next(Int32.MaxValue).ToString();
return DateTime.Now.ToShortDateString() + "_" + s + ".csv";
}
#endregion
}
}
c# DataTable 导出csv文件的更多相关文章
- 每日学习心得:Linq解决DataTable按照某一列的值排序问题/DataTable 导出CSV文件/巧用text-overflow解决数据绑定列数据展示过长问题
2013-8-5 1 Linq解决DataTable按照某一列的值排序 在之前的总结中提到过对拼接而成的复合的DataTable按照某一列值的大小排序,那个主要的思想是在新建表结构时将要排序的那一列的 ...
- C#将DataTable数据导出CSV文件
C#将DataTable数据导出CSV文件通用方法! //导出按钮调用导出方法 protected void btnCSV_Click(object sender, EventArgs e) ...
- 导出csv文件示例
导出csv文件示例 csv文件默认以英文逗号,做为列分隔符换行符\n作为行分隔符,写入到一个.csv文件即可.含有英文逗号,和换行符会发生数据输出会出现混乱,下面列出一些处理方法.特殊字符处理1.含有 ...
- mysql SQLyog导入导出csv文件
1.选择数据库表 --> 右击属性 --> 备份/导出 --> 导出表数据作为 --> 选择cvs --> 选择下面的“更改” --> 字段 --> 变量长度 ...
- PHP 读取/导出 CSV文件
工作中经常会有遇到导入/导出的需求,下面是常用的方法.读取CSV文件,可以分页读取,设置读取行数,起始行数即可.导出CSV文件,用两种方法进行实现. /** * 读取CSV文件 * @param st ...
- Web 端 js 导出csv文件(使用a标签)
前言 导出文件,使用最多的方式还是服务器端来处理.比如jsp 中使用response 的方式. 但是,有时候可能就想使用web 前端是否也可以把页面上的内容导出来呢? 比如说,导出页面的一个表格. 这 ...
- PHP导出CSV文件出现乱码的解决方法
在做项目时碰到使用外语的情况下,我们就会使用UTF-8编码.但是,在用PHP导出CSV文件时,如果写入的数据是使用UTF-8编码的日语.韩语之类的外文,就会出现乱码. 要解决PHP生成CSV文件的乱码 ...
- [转]PL/SQL Developer 导入导出csv文件
PL/SQL Developer 可以导入或者导出CSV文件. 导入CSV文件步骤: 1.选择tools->text importer.... 2.选择第二个Data to oracle选项卡, ...
- 导出csv文件数字会自动变科学计数法的解决方法
其实这个问题跟用什么语言导出csv文件没有关系.Excel显示数字时,如果数字大于12位,它会自动转化为科学计数法:如果数字大于15位,它不仅用于科学技术费表示,还会只保留高15位,其他位都变0.解决 ...
随机推荐
- Autowire
Field userService in com.demo.web.Controller.HomeController required a single bean, but 2 were found ...
- Oracle数据库创建表ID字段的自动递增
转载地址:http://blog.itpub.net/22880668/viewspace-1117343/ 将表t_uaer的字段ID设置为自增:(用序列sequence的方法来实现) ----创建 ...
- STL学习笔记(不定期更新)
algorithm *1.sort() 用法:sort(数组名,名+长度(,cmp)); int cmp(T a,T b)//T是要排序的a,b的类型,也可以是结构体中任意成员变量 { return ...
- git重命名分支名
git branch -m old_branch_name new_branch_name
- 解决IE6已终止操作问题
令人崩溃的IE6问题再次出现,打开某个页面时,弹出提示框“Internet Explorer无法打开Internet 站点...已终止操作”. 查了一下资料,感觉“因为js(一个比较复杂的js) ...
- 推荐个非常简单好用的AOP -- MrAdvice
https://github.com/ArxOne/MrAdvice 太简单了,写好自己的处理类, 作为Attribute加到要拦截的方法或者类上就可以了. Here is the minimal s ...
- Juniper SRX 简单命令一
Juniper为人所熟悉的一定是从netscreen开始的,作为一线防火墙品牌,还是有很高的地位.但是以前玩netscreen,都是用的网页版去配置,而且网页版做得很不错.但是现在netscreen要 ...
- 使用vs的时候,遇到这个:当前不会命中断点 还没有为该文档加载任何符号
一 http://stackoverflow.com/questions/2155930/fixing-the-breakpoint-will-not-currently-be-hit-no-symb ...
- ZJOI2017游记
$Day$ $-1$ 听说可以去$ZJOI2017$打酱油,终于可以出去走走辣$QAQ$... 上次出去打比赛似乎是$PKUSC$?? 好吧,至少可以一览国家预备队爷们的风采... 准备把膝盖留在浙江 ...
- htop 比top更好用的top
安装 sudo apt-get install htop 使用 htop