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.解决 ...
随机推荐
- Python3.x:chrome运行webdriver脚本提示--ignore-certificate-errors
Python3.x:chrome运行webdriver脚本提示--ignore-certificate-errors 1,分析原因: 根本原因是Chromedriver和Chrome的版本不兼容: 网 ...
- nginx之rewrite匹配需求
现在需求如下: nginx上配有aaa.example.com的虚拟主机,现在需要将访问http://aaa.example.com/api/x.x/client/的请求转到http://bbb.ex ...
- linux 下各个头文件的作用[典]
linux 下各个头文件的作用 2.6.30.4的头文件的位置和2.6.25.8的不一样,除去内核源码下的include目录外, 在arch/arm/mach-s3c2410/和arch/arm/ ...
- 【转载】JExcelApi(JXL)学习笔记
在公司的项目中,有excel生成.导出的需求,因此学习了用JXL读写excel,做个简单的笔记,以供参考. 实现用java操作excel的工具,一般用的有两个:一个是JXL,另一个是apac ...
- Nginx配置X-Forwarded-Proto
需求 最近公司在做全站https,架构上面有Nginx+tomcat Nginx+php,且nginx配置了ssl,tomcat和php项目使用https协议 但是,发送的是https url请求,p ...
- mybatis缓存有关的设置和属性
知识点:mybatis缓存相关的设置和属性 重点:每次执行增删改操作后,一二级缓存被清空,是因为标签设置默认属性为 flushCache="true" (1) <!-- 全局 ...
- 贯众云平台脚本编写之判断、循环以及shell命令的使用
最近使用贯众云平台工具写脚本,进行Ui界面的自动化测试.刚开始接触,确实碰到不少的问题,稍微难点的就是判断语句,循环语句以及shell命令的使用,尤其是对于咱们测试这样比较少接触代码的人来说. 其实吧 ...
- 机器学习笔记—Logistic 回归
前面我们介绍了线性回归,为捕获训练集中隐藏的线性模型,提高预测准确率,我们寻找最佳参数 θ,使得预测值与真实值误差尽量小,也就是使均方误差最小.而经过验证,最小均方误差是符合最大似然估计理论的. 在 ...
- python一个元素全为数的列表做差分
woc = [7, 5, 7, 3, 5, 1, 2] diff = [ wo[i]-wo[i+1] for i in range(len(wo)-1) ]
- LeetCode第[98]题(Java):Validate Binary Search Tree(验证二叉搜索树)
题目:验证二叉搜索树 难度:Medium 题目内容: Given a binary tree, determine if it is a valid binary search tree (BST). ...