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.解决 ...
随机推荐
- 照着官网来安装openstack pike之glance安装
镜像服务image service(glance)的安装还是在控制节点上进行: 1.前提条件,数据库为glance创建库和账户密码来连接数据库 # mysql -u root -p MariaDB [ ...
- 20145310 GDB调试汇编堆栈分析
GDB调试汇编堆栈分析 由于老师说要逐条分析汇编代码,所以我学习卢肖明同学的方法,重新写了一篇博客. 代码: #include<stdio.h> short addend1 = 1; st ...
- ubuntu下源码安装wget
1.背景 ubuntu18.04 64bit 2.安装方法如下: 2.1.获取源码 curl -o wget-1.20.tar.gz ftp://ftp.gnu.org/gnu/wget/wget-1 ...
- [CF1051F]The Shortest Statement
题目大意:给定一张$n$个点$m$条有权边的无向联通图,$q$次询问两点间的最短路 $n\le100000$,$m\le100000$,$1\le100000$,$m$-$n\le20$. 首先看到$ ...
- SaltStack介绍及简单配置-第一篇
SaltStack介绍 一种全新的基础设施管理方式,部署轻松,在几分钟内可运行起来,扩展性好,很容易管理上万台服务器,速度够快,服务器之间秒级通讯. salt底层采用动态的连接总线, 使其可以用于编配 ...
- LeetCode——Find Duplicate Subtrees
Question Given a binary tree, return all duplicate subtrees. For each kind of duplicate subtrees, yo ...
- Windows下实现mysql定时备份
1.写MySQL备份bat处理 @echo off set "yMd=%date:~,4%%date:~5,2%%date:~8,2%" set "hms=%time:~ ...
- Java的历史及发展
Java之父:詹姆斯·高斯林 (James Gosling) Java自1995诞生,至今已经20多年的历史. Java的名字的来源:Java是印度尼西亚爪哇岛的英文名称,因盛产咖啡而闻名.Java语 ...
- 随笔分类 - java高级特性
转自:http://www.cnblogs.com/linjiqin/category/282013.html
- 使用ssm整合是项目启动tomcat报错java.lang.IndexOutOfBoundsException
解决办法:删除.m2文件夹下的全部仓库,然后重启myeclipse,对项目进行maven project.问题解决. 在没有这样做时,除了tomcat启动会失败,项目还有会报如下错误: ①cvc-co ...