数据里经常有些特殊的字符,例如“,”如果导出.CSV很容易出现串列错误。所以要做限制转换一下
public void ExportToSvc(System.Data.DataTable dt, string strFileName)
{
string strPath = strFileName;
if (File.Exists(strPath))
{
File.Delete(strPath);
}
//先打印标头
StringBuilder strColu = new StringBuilder();
StringBuilder strValue = new StringBuilder();
int i = 0;
try
{
StreamWriter sw = new StreamWriter(new FileStream(strPath, FileMode.CreateNew), 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(ReplaceChar(dr[i] == DBNull.Value ? "" : dr[i].ToString()));
strValue.Append(",");
}
strValue.Remove(strValue.Length - 1, 1);//移出掉最后一个,字符
sw.WriteLine(strValue.ToString());
}
sw.Close();
}
catch (Exception ex)
{
throw ex;
}
}
//防止串列
private string ReplaceChar(string str)
{
string field = str;
if (field.IndexOf("+") == 0 || field.IndexOf("-") == 0 || field.IndexOf("=") == 0 || field.IndexOf("'") == 0)
{
if (IsNum(field))
{
return field;
}
return string.Format("\t{0}", field);
}
if (field.IndexOf(',') >= 0)
{
return string.Format("\"{0}\"", field);
}
if (field.IndexOf('"') >= 0)
{
return string.Format("\t{0}", field);
}
if (field.IndexOf('\r') >= 0)
{
return string.Format("\"{0}\"", field);
}
if (field.IndexOf('\n') >= 0)
{
return string.Format("\"{0}\"", field);
}
if (field.IndexOf('\"') >= 0)
{
return string.Format("\"{0}\"", field);
}
if (field != field.Trim())
{
return string.Format("\"{0}\"", field);
}
return field;
}
private bool IsNum(object num)
{
try
{
Convert.ToDecimal(num);
return true;
}
catch
{
return false;
}
}