C#操作CSV存取类

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Windows.Forms;
using System.IO;
namespace FileReadAndWrite
{
     <summary>
     操作CSV存取类
     </summary>
    public class OutForCVS
    {
        #region 变量
         <summary>
         取出配置文件中的分隔符
         </summary>
        private static string _splitChar = null;
         <summary>
         取出配置文件中的编码方式
         </summary>
        private static string _encodeFormat = null;
        #endregion
        #region 构造方法
         <summary>
         构造方法获取分隔符、编码方式
         </summary>
       
        #endregion
        #region 写CSV方法
         <summary>
         写入CSV
         </summary>
         <param name="hasHeader">列头</param>
         <param name="dtOutputCSV">文件内容</param>
        public void WriteCSV(bool hasHeader, DataTable dtOutputCSV)
        {
             Log开始
            INGLog.WriteLog(INGLogLevel.Debug, INGConstants.START);
             获取写入文件名称以及格式
            String strFileName = DateTime.Now.ToString("YYYYMMDDhhmm");
            SaveFileDialog savFileDialog = new SaveFileDialog();
            savFileDialog.Reset();
            savFileDialog.DefaultExt = "csv";
            savFileDialog.Filter = "CSV|*.csv";
            savFileDialog.ShowDialog();
            strFileName = savFileDialog.FileName;
             判断文件名
            if (string.IsNullOrEmpty(strFileName))
            {
                 信息提示
                INGMessage.ShowMessage("M009", "WriteFileName");
            }
             重载方法调用,写入文件
            WriteCSV(hasHeader, dtOutputCSV, strFileName+".csv");
             Log结束
            INGLog.WriteLog(INGLogLevel.Debug, INGConstants.END);
        }
        #endregion
        #region 写入CSV,附带路径方法
         <summary>
         写入CSV,附带路径
         </summary>
         <param name="hasHeader">列头</param>
         <param name="dtOutputCSV">文件内容</param>
         <param name="strPath">指定文件路径</param>
        public static void WriteCSV(bool hasHeader, DataTable dtOutputCSV, string strPath)
        {
             Log开始
            INGLog.WriteLog(INGLogLevel.Debug, INGConstants.START);
             DataTable有无判断
            if (dtOutputCSV == null)
            {
                throw new ArgumentNullException("Argument(dtOutputCSV) is null!");
            }
             StringBuilder初始化
            StringBuilder sb = new StringBuilder();
             DataTable有无数据判断
            if (hasHeader)
            {
                添加列头
                foreach (DataColumn dc in dtOutputCSV.Columns)
                {
                    if (dc.DataType == Type.GetType("System.String"))
                    {
                        dc.ColumnName = "'" + dc.ColumnName + "'"; //修改
                    }
                    sb.Append(dc.ColumnName).Append(_splitChar);
                }
                 创建新行
                sb.Remove(sb.Length - 1, 1);
                sb.Append(Environment.NewLine);
            }
             路径为空或者取消保存时
            if (strPath == "")
            {
                return;
            }
             添加行
            foreach (DataRow dr in dtOutputCSV.Rows)
            {
                foreach (object rowItem in dr.ItemArray)//object rowItem
                {
                    object itemValue = rowItem;
                    itemValue = "'" + itemValue + "'";
                    sb.Append(itemValue).Append(_splitChar);
                }
                 创建新行
                sb.Remove(sb.Length - 1, 1);
                sb.Append(Environment.NewLine);
            }
            using (TextWriter tw = new StreamWriter(strPath, false))
            {
                tw.Write(sb.ToString());
                INGMessage.ShowMessage("M010", "Success");
                tw.Flush();
                tw.Close();
            }
             Log结束
            INGLog.WriteLog(INGLogLevel.Debug, INGConstants.END);
        }
        #endregion
        #region 读CSV文件方法
        /// <summary>
        /// 读CSV文件
        /// </summary>
        /// <param name="hasHeader">列头</param>
        /// <returns>返回信息</returns>
        public static DataTable ReadCSV(bool hasHeader)
        {
            // Log开始
            //INGLog.WriteLog(INGLogLevel.Debug, INGConstants.START);
            String strFileName;
            using (OpenFileDialog ofdFileDialog = new OpenFileDialog())
            {
                ofdFileDialog.Reset();
                ofdFileDialog.DefaultExt = "csv";
                ofdFileDialog.Filter = "CSV|*.csv";
                ofdFileDialog.ShowDialog();
                // 文件名取得
                strFileName = ofdFileDialog.FileName;
            }
            // 文件路径取得
            String strFilePath = Path.GetFileName(strFileName);
            // 文件路径判断
            if (string.IsNullOrEmpty(strFilePath))
            {
                return null;
            }
            // Log结束
            //INGLog.WriteLog(INGLogLevel.Debug, INGConstants.END);
            return ReadCSV(hasHeader, strFilePath);
        }
        #endregion
        #region 读指定路径CSV文件方法
         <summary>
         读指定路径CSV文件
         </summary>
         <param name="hasHeader">列头</param>
         <param name="strPath">指定文件路径</param>
         <returns>返回信息</returns>
        public static DataTable ReadCSV(bool hasHeader, string strPath)
        {
            // Log开始
            //INGLog.WriteLog(INGLogLevel.Debug, INGConstants.START);
            String FileName = Path.GetFileName(strPath);
            // 文件路径判断
            if (string.IsNullOrEmpty(FileName))
            {
                return null;
            }
            DataTable dt = new DataTable(FileName);
            // 文本文件分析instance生成
            TextFieldParser parser = new TextFieldParser(strPath, Encoding.GetEncoding(_encodeFormat));
            // 指定文件形式
            parser.TextFieldType = FieldType.Delimited;
            // 段落分割
            parser.SetDelimiters(_splitChar);
            // 设置CSV行计数
            int iRowCnt = 0;
            // 到文件最后边界   
            while (!parser.EndOfData)
            {
                // 读入一行
                string[] row = parser.ReadFields();
                // CSV行判断
                if (iRowCnt.Equals(0))
                {
                    // 判断列头有无
                    if (hasHeader)
                    {
                        int i = 0;
                        // 添加列到行
                        foreach (string sColumn in row)
                        {
                            // DataColumn初始化
                            DataColumn column = new DataColumn();
                            column.DataType = Type.GetType("System.String");
                            string sColumnValue = sColumn;
                            sColumnValue = sColumnValue.Substring(1, sColumnValue.Length - 2);
                            column.ColumnName = sColumnValue;
                            dt.Columns.Add(column);
                        }
                    }
                }
                // 数据
                else //修改
                {
                    // 行添加
                    int rowLength = row.Length;
                    DataRow dr = dt.NewRow();
                    for (int j = 0; j < rowLength; j++)
                    {
                        string columnValue = row.GetValue(j).ToString();
                        columnValue = columnValue.Substring(1, columnValue.Length - 2);
                        dr[j] = columnValue;
                    }
                    dt.Rows.Add(dr);
                }
                // CSV行计数
                iRowCnt++;
            }
            // Log结束
            INGLog.WriteLog(INGLogLevel.Debug, INGConstants.END);
            return dt;
        }
        #endregion
        public void CreateCsv(System.Data.DataTable dt, string strName)
        {
 
            先打印标头
            StringBuilder strColu = new StringBuilder();
            StringBuilder strValue = new StringBuilder();
            int i = 0;
            try
            {
                StreamWriter sw = new StreamWriter(new FileStream(strName + ".csv", FileMode.Create), Encoding.GetEncoding("GB2312"));
                for (i = 0; i <= dt.Columns.Count - 1; i++)
                {
                    strColu.Append("\"" + dt.Columns[i].ColumnName + "\"");
                    strColu.Append(",");
                }
                strColu.Remove(strColu.Length - 1, 1);//移出掉最后一个,字符
                sw.WriteLine(strColu);
                foreach (DataRow dr in dt.Rows)
                {
                    strValue.Remove(0, strValue.Length);//移出
                    for (i = 0; i <= dt.Columns.Count - 1; i++)
                    {
                        strValue.Append("\"" + dr[i].ToString().Replace("'", "''").Replace(",", "") + "\"");
                        strValue.Append(",");
                    }
                    strValue.Remove(strValue.Length - 1, 1);//移出掉最后一个,字符
                    sw.WriteLine(strValue);
                }
                sw.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

    }
}

 

之前所写,迁移至此

原文链接:http://user.qzone.qq.com/372806800/blog/1345305065

posted @ 2017-01-04 13:58  风来风往风伤(TiAmo)  阅读(3345)  评论(0编辑  收藏  举报