国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > C# > 正文

C#導出數據到CSV文件的通用類實例

2020-01-24 01:58:16
字體:
來源:轉載
供稿:網友

本文實例講述了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#程序設計有所幫助。

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 乐昌市| 榕江县| 江北区| 华坪县| 全椒县| 理塘县| 金门县| 紫云| 乐昌市| 梅州市| 原阳县| 玛多县| 高平市| 漠河县| 东明县| 岳阳市| 泰宁县| 建昌县| 通河县| 扶风县| 辰溪县| 海宁市| 临城县| 景泰县| 措美县| 茌平县| 苗栗市| 南通市| 绥江县| 临夏市| 长岭县| 通渭县| 隆安县| 井冈山市| 崇义县| 巨鹿县| 曲松县| 济南市| 罗田县| 金平| 白朗县|