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 + "\"";
}
}
}