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文件的更多相关文章

  1. 每日学习心得:Linq解决DataTable按照某一列的值排序问题/DataTable 导出CSV文件/巧用text-overflow解决数据绑定列数据展示过长问题

    2013-8-5 1 Linq解决DataTable按照某一列的值排序 在之前的总结中提到过对拼接而成的复合的DataTable按照某一列值的大小排序,那个主要的思想是在新建表结构时将要排序的那一列的 ...

  2. C#将DataTable数据导出CSV文件

    C#将DataTable数据导出CSV文件通用方法! //导出按钮调用导出方法    protected void btnCSV_Click(object sender, EventArgs e)   ...

  3. 导出csv文件示例

    导出csv文件示例 csv文件默认以英文逗号,做为列分隔符换行符\n作为行分隔符,写入到一个.csv文件即可.含有英文逗号,和换行符会发生数据输出会出现混乱,下面列出一些处理方法.特殊字符处理1.含有 ...

  4. mysql SQLyog导入导出csv文件

    1.选择数据库表 --> 右击属性 --> 备份/导出 --> 导出表数据作为 --> 选择cvs --> 选择下面的“更改” --> 字段 --> 变量长度 ...

  5. PHP 读取/导出 CSV文件

    工作中经常会有遇到导入/导出的需求,下面是常用的方法.读取CSV文件,可以分页读取,设置读取行数,起始行数即可.导出CSV文件,用两种方法进行实现. /** * 读取CSV文件 * @param st ...

  6. Web 端 js 导出csv文件(使用a标签)

    前言 导出文件,使用最多的方式还是服务器端来处理.比如jsp 中使用response 的方式. 但是,有时候可能就想使用web 前端是否也可以把页面上的内容导出来呢? 比如说,导出页面的一个表格. 这 ...

  7. PHP导出CSV文件出现乱码的解决方法

    在做项目时碰到使用外语的情况下,我们就会使用UTF-8编码.但是,在用PHP导出CSV文件时,如果写入的数据是使用UTF-8编码的日语.韩语之类的外文,就会出现乱码. 要解决PHP生成CSV文件的乱码 ...

  8. [转]PL/SQL Developer 导入导出csv文件

    PL/SQL Developer 可以导入或者导出CSV文件. 导入CSV文件步骤: 1.选择tools->text importer.... 2.选择第二个Data to oracle选项卡, ...

  9. 导出csv文件数字会自动变科学计数法的解决方法

    其实这个问题跟用什么语言导出csv文件没有关系.Excel显示数字时,如果数字大于12位,它会自动转化为科学计数法:如果数字大于15位,它不仅用于科学技术费表示,还会只保留高15位,其他位都变0.解决 ...

随机推荐

  1. 【Thinking in Java, 4e】访问权限控制

    [包:库单元] 编译单元的概念. 一个.java文件就是一个编译单元,一个编译单元只能有一个public类,编译单元中的非public类一般是用于为public类提供支持的,这些类在包外不可见. im ...

  2. go基础语法

    定义变量: 可放在函数内,或直接放在包内使用var集中定义变量使用:=定义变量写的短一些 package main import ( "fmt" "math" ...

  3. left4dead2 常用配置

    难度控制 z_difficulty [Easy, Normal, Hard, Impossible]

  4. 构造函数挨个过 —— String()

    本篇整理JavaScript中构造函数String的相关知识,主要分为以下三个部分: 构造函数String()的作用与使用方式: String()的属性和方法: 字符串对象实例属性和方法: 一 构造函 ...

  5. 解读:MultipleOutputs类

    //MultipleOutputs类用于简化多文件输出The MultipleOutputs class simplifies writing output data to multiple outp ...

  6. [翻译]解读CSS中的长度单位

    测量,在WEB设计上是非常重要的.在CSS中有至少10种不同的测量单位.每种单位都有其独特的作用,使用它们,可以使页面,在各种设备上,很好的工作.一旦你熟悉了所有这些单位,你可以更准确地设定元素的大小 ...

  7. Linux禁止普通用户使用crontab命令

    cron计划任务默认root用户与非root用户都可以执行,当然如果在安全方面想禁用这部分用户,则可以通过两个文件来解决: cron.allow cron.deny cron.allow:定义允许使用 ...

  8. centos查看是否安装了某个软件

    1. rpm包安装的,可以用rpm -qa看到,如果要查找某软件包是否安装,用 rpm -qa | grep "软件或者包的名字". 2. yum方法安装的,可以用yum list ...

  9. Elasticsearch之中文分词器

    前提 什么是倒排索引? Elasticsearch之分词器的作用 Elasticsearch之分词器的工作流程 Elasticsearch之停用词 Elasticsearch的中文分词器 1.单字分词 ...

  10. HTML请求与相应

    HTTP的请求与响应 HTTP通信由两部分组成: 客户端请求消息 与 服务器响应消息 浏览器发送HTTP请求的过程: 当用户在浏览器的地址栏中输入一个URL并按回车键之后,浏览器会向HTTP服务器发送 ...