1. 程式人生 > >C# CSV檔案操作

C# CSV檔案操作

using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
/*****************************
 * 概要:CSV檔案操作
 * 設計者:DuanXuWen
 * 設計時間:20180309
 * 版本:0.1
 * 修改者:
 * 修改時間:
 * ***************************/

namespace Common
{
    public class CSVHelper
    {
        /// <summary>
        /// 匯出CSV檔案
        /// </summary>
        /// <param name="dt"></param>
        /// <param name="pathFile"></param>
        /// <returns></returns>
        public static void DataTableToCSV(DataTable dt, string pathFile)
        {
            string strLine = "";
            StreamWriter sw;
            try
            {
                sw = new StreamWriter(pathFile, false, System.Text.Encoding.GetEncoding(-0)); //覆蓋
                //表頭
                for (int i = 0; i < dt.Columns.Count; i++)
                {
                    if (i > 0)
                        strLine += ",";
                    strLine += dt.Columns[i].ColumnName;
                }
                strLine.Remove(strLine.Length - 1);
                sw.WriteLine(strLine);
                strLine = "";
                //表的內容
                for (int j = 0; j < dt.Rows.Count; j++)
                {
                    strLine = "";
                    int colCount = dt.Columns.Count;
                    for (int k = 0; k < colCount; k++)
                    {
                        if (k > 0 && k < colCount)
                            strLine += ",";
                        if (dt.Rows[j][k] == null)
                            strLine += "";
                        else
                        {
                            strLine += FormatCell(dt.Rows[j][k].ToString().Trim());
                        }
                    }
                    sw.WriteLine(strLine);
                }
                sw.Close();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// 判斷字串是否包含奇數個引號
        /// </summary>
        /// <param name="dataLine">資料行</param>
        /// <returns>為奇數時,返回為真;否則返回為假</returns>
        private bool IfOddQuota(string dataLine)
        {
            int quotaCount;
            bool oddQuota;
            quotaCount = 0;
            for (int i = 0; i < dataLine.Length; i++)
            {
                if (dataLine[i] == '\"')
                {
                    quotaCount++;
                }
            }
            oddQuota = false;
            if (quotaCount % 2 == 1)
            {
                oddQuota = true;
            }
            return oddQuota;
        }

        /// <summary>
        /// 判斷是否以奇數個引號開始
        /// </summary>
        /// <param name="dataCell"></param>
        /// <returns></returns>
        private bool IfOddStartQuota(string dataCell)
        {
            int quotaCount;
            bool oddQuota;
            quotaCount = 0;
            for (int i = 0; i < dataCell.Length; i++)
            {
                if (dataCell[i] == '\"')
                {
                    quotaCount++;
                }
                else
                {
                    break;
                }
            }
            oddQuota = false;
            if (quotaCount % 2 == 1)
            {
                oddQuota = true;
            }
            return oddQuota;
        }

        /// <summary>
        /// 判斷是否以奇數個引號結尾
        /// </summary>
        /// <param name="dataCell"></param>
        /// <returns></returns>
        private bool IfOddEndQuota(string dataCell)
        {
            int quotaCount;
            bool oddQuota;
            quotaCount = 0;
            for (int i = dataCell.Length - 1; i >= 0; i--)
            {
                if (dataCell[i] == '\"')
                {
                    quotaCount++;
                }
                else
                {
                    break;
                }
            }
            oddQuota = false;
            if (quotaCount % 2 == 1)
            {
                oddQuota = true;
            }
            return oddQuota;
        }

        /// <summary>
        /// 字串轉換成CSV中的格子
        /// 雙引號轉換成兩個雙引號,然後首尾各加一個雙引號
        /// 這樣就不需要考慮逗號及換行的問題
        /// </summary>
        /// <param name="cell">格子內容</param>
        /// <returns></returns>
        private static string FormatCell(string cell)
        {
            cell = cell.Replace("\"", "\"\"");
            if (ValidateHelper.ValidateFormat(Format.Number,cell))
            {
                cell = "\t" + cell;
            }
            return "\"" + cell + "\"";
        }
    }
}