110,546
社区成员
发帖
与我相关
我的任务
分享
#region 导出电子表格
// StreamWriter 参数说明:
// path:
// The complete file path to write to.
//
// append:
// Determines whether data is to be appended to the file. If the file exists
// and append is false, the file is overwritten. If the file exists and append
// is true, the data is appended to the file. Otherwise, a new file is created.
//
// encoding:
// The character encoding to use.
//导出 DataTable 到 Excel
public static void SaveDataToCVS(DataTable dt, string fileName,out string strmsg)
{
using (StreamWriter sw = new StreamWriter(fileName, false, Encoding.Default))
{
string line;
try
{
foreach (DataRow dr in dt.Rows)
{
line = GenerateLine(dr);
sw.WriteLine(line);
}
strmsg = "OK";
}
catch (Exception)
{
strmsg = "导出EXCEL失败!";
return;
}
}
}
//对定界符和逗号进行处理
private static string GenerateLine(DataRow dr)
{
string retLine = string.Empty; //相当于 "",但是不分配空间
string field = string.Empty;
try
{
foreach (DataColumn dc in dr.Table.Columns)
{
//取字段文本
field = dr[dc.ColumnName].ToString();
//如果存在双引号,就将一个双引号变成两个双引号
if (field.IndexOf('"') >= 0)
{
field = field.Replace("\"", "\"\"");
}
//如果字段中含有逗号或者双引号,就要将这个字段用双引号括起来
if (field.IndexOf(',') >= 0 || field.IndexOf('"') >= 0)
{
field = "\"" + field + "\"";
}
//增加分隔符
retLine += field + ",";
field = string.Empty;
}
//去除最后一个逗号并返回
return retLine.TrimEnd(',');
}
catch (Exception ex)
{
throw(ex);
}
}
#endregion 导出电子表格