欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

C#导出数据到CSV文件的通用类实例

程序员文章站 2023-10-26 23:48:16
本文实例讲述了c#导出数据到csv文件的通用类。分享给大家供大家参考。具体如下: 通过这个类可以很简单的定义数据格式,并导出到csv文件 //这里写了一个通用的...

本文实例讲述了c#导出数据到csv文件的通用类。分享给大家供大家参考。具体如下:

通过这个类可以很简单的定义数据格式,并导出到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 com.drpeng.sdxy.ui.common
{
 public class csvhelper
 {
  #region fields
  string _filename;
  datatable _datasource;//数据源
  string[] _titles = null;//列标题
  string[] _fields = null;//字段名
  #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;
  }
  /// <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;
  }
  /// <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 void datatocsv(string filename)
  {
   // 确保有一个合法的输出文件名 
   //if (filename == null || filename == string.empty || !(filename.tolower().endswith(".csv")))
   // filename = getrandomfilename();
   string data = exportcsv();
   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(_fields[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#程序设计有所帮助。