欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

C#導(dǎo)出數(shù)據(jù)到CSV文件的通用類(lèi)實(shí)例

 更新時(shí)間:2015年04月21日 09:01:58   作者:js達(dá)人  
這篇文章主要介紹了C#導(dǎo)出數(shù)據(jù)到CSV文件的通用類(lèi),將C#操作CSV文件的常用技巧封裝進(jìn)一個(gè)通用類(lèi)中以方便調(diào)用,非常具有實(shí)用價(jià)值,需要的朋友可以參考下

本文實(shí)例講述了C#導(dǎo)出數(shù)據(jù)到csv文件的通用類(lèi)。分享給大家供大家參考。具體如下:

通過(guò)這個(gè)類(lèi)可以很簡(jiǎn)單的定義數(shù)據(jù)格式,并導(dǎo)出到csv文件

//這里寫(xiě)了一個(gè)通用的類(lèi)
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;//數(shù)據(jù)源
  string[] _titles = null;//列標(biāo)題
  string[] _fields = null;//字段名
  #endregion
  #region .ctor
  /// <summary> 
  /// 構(gòu)造函數(shù) 
  /// </summary> 
  /// <param name="dataSource">數(shù)據(jù)源</param> 
  public CSVHelper()
  {
  }
  /// <summary> 
  /// 構(gòu)造函數(shù) 
  /// </summary> 
  /// <param name="titles">要輸出到 Excel 的列標(biāo)題的數(shù)組</param> 
  /// <param name="fields">要輸出到 Excel 的字段名稱(chēng)數(shù)組</param> 
  /// <param name="dataSource">數(shù)據(jù)源</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> 
  /// 構(gòu)造函數(shù) 
  /// </summary> 
  /// <param name="titles">要輸出到 Excel 的列標(biāo)題的數(shù)組</param> 
  /// <param name="dataSource">數(shù)據(jù)源</param> 
  public CSVHelper(string[] titles, DataTable dataSource)
   : this(dataSource)
  {
   if (titles == null || titles.Length == 0)
    throw new ArgumentNullException("titles");
   _titles = titles;
  }
  /// <summary> 
  /// 構(gòu)造函數(shù) 
  /// </summary> 
  /// <param name="dataSource">數(shù)據(jù)源</param> 
  public CSVHelper(DataTable dataSource)
  {
   if (dataSource == null)
    throw new ArgumentNullException("dataSource");
   // maybe more checks needed here (IEnumerable, IList, IListSource, ) ??? 
   // 很難判斷,先簡(jiǎn)單的使用 DataTable 
   _dataSource = dataSource;
  }
  #endregion
  #region public Methods
  #region 導(dǎo)出到CSV文件并且提示下載
  /// <summary>
  /// 導(dǎo)出到CSV文件并且提示下載
  /// </summary>
  /// <param name="fileName"></param>
  public void DataToCSV(string fileName)
  {
   // 確保有一個(gè)合法的輸出文件名 
   //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導(dǎo)入的數(shù)據(jù)
  /// </summary>
  /// <param name="filePath">文件路徑</param>
  /// <param name="fileName">文件名稱(chēng)(.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 返回寫(xiě)入CSV的字符串
  /// <summary>
  /// 返回寫(xiě)入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 得到一個(gè)隨意的文件名
  /// <summary> 
  /// 得到一個(gè)隨意的文件名 
  /// </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
 }
}

希望本文所述對(duì)大家的C#程序設(shè)計(jì)有所幫助。

相關(guān)文章

  • c# 線(xiàn)程定時(shí)器 System.Threading.Timer的使用

    c# 線(xiàn)程定時(shí)器 System.Threading.Timer的使用

    本文主要介紹了c# 線(xiàn)程定時(shí)器 System.Threading.Timer的使用,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2023-02-02
  • c#后臺(tái)輸出javascript語(yǔ)句示例程序

    c#后臺(tái)輸出javascript語(yǔ)句示例程序

    一個(gè)很不錯(cuò)的b/s前臺(tái)輸出彈出對(duì)話(huà)框、后臺(tái)寫(xiě)javascript語(yǔ)句、后臺(tái)直接關(guān)閉web頁(yè)面及一個(gè)集成了常用驗(yàn)證的通用類(lèi),十分的方便。代碼如下
    2013-12-12
  • C#調(diào)用新浪微博API實(shí)例代碼

    C#調(diào)用新浪微博API實(shí)例代碼

    在本篇文章里小編給大家整理的是一篇關(guān)于C#調(diào)用微博API的相關(guān)知識(shí)點(diǎn)內(nèi)容,有需要的朋友們可以學(xué)習(xí)下。
    2019-11-11
  • c# 使用handle.exe解決程序更新文件被占用的問(wèn)題

    c# 使用handle.exe解決程序更新文件被占用的問(wèn)題

    這篇文章主要介紹了c# 使用handle.exe解決程序更新文件被占用的問(wèn)題,幫助大家更好的理解和學(xué)習(xí)使用c#,感興趣的朋友可以了解下
    2021-03-03
  • C#正則表達(dá)式Regex用法詳解

    C#正則表達(dá)式Regex用法詳解

    本文詳細(xì)講解了C#正則表達(dá)式Regex的用法,文中通過(guò)示例代碼介紹的非常詳細(xì)。對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2022-06-06
  • C#實(shí)現(xiàn)順序隊(duì)列和鏈隊(duì)列的代碼實(shí)例

    C#實(shí)現(xiàn)順序隊(duì)列和鏈隊(duì)列的代碼實(shí)例

    今天小編就為大家分享一篇關(guān)于C#實(shí)現(xiàn)順序隊(duì)列和鏈隊(duì)列的代碼實(shí)例,小編覺(jué)得內(nèi)容挺不錯(cuò)的,現(xiàn)在分享給大家,具有很好的參考價(jià)值,需要的朋友一起跟隨小編來(lái)看看吧
    2018-10-10
  • C#使用HttpWebRequest重定向方法詳解

    C#使用HttpWebRequest重定向方法詳解

    在本篇內(nèi)容里小編給讀者們整理了關(guān)于C#使用HttpWebRequest重定向方法和相關(guān)知識(shí)點(diǎn),需要的朋友們參考下。
    2019-03-03
  • C#驗(yàn)證控件validator的簡(jiǎn)單使用

    C#驗(yàn)證控件validator的簡(jiǎn)單使用

    這篇文章主要介紹了C#驗(yàn)證控件validator的簡(jiǎn)單使用方法和示例,十分的簡(jiǎn)單實(shí)用,有需要的小伙伴可以參考下。
    2015-06-06
  • c# 實(shí)現(xiàn)簡(jiǎn)單的串口通訊

    c# 實(shí)現(xiàn)簡(jiǎn)單的串口通訊

    這篇文章主要介紹了c# 如何實(shí)現(xiàn)簡(jiǎn)單的串口通訊,幫助大家更好的理解和學(xué)習(xí)使用c#,感興趣的朋友可以了解下
    2021-03-03
  • 簡(jiǎn)單C#代碼實(shí)現(xiàn)modbus-rtu通訊發(fā)送數(shù)據(jù)方式

    簡(jiǎn)單C#代碼實(shí)現(xiàn)modbus-rtu通訊發(fā)送數(shù)據(jù)方式

    這篇文章主要介紹了簡(jiǎn)單C#代碼實(shí)現(xiàn)modbus-rtu通訊發(fā)送數(shù)據(jù)方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2024-01-01

最新評(píng)論