博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

导出CSV文件

Posted on 2017-08-22 16:45  first_start  阅读(260)  评论(0)    收藏  举报

/// <summary>
/// 导出CSV文件
/// </summary>
/// <param name="savePath">保存名</param>
/// <param name="dtData">数据</param>
/// <param name="colCount">导出数据的列数</param>
public static void ExportCSVFile(string savePath, DataRow[] dtData, int colCount = 0)
{
if (dtData.Length > 0)
{
if (colCount.Equals(0) || colCount > dtData[0].ItemArray.Length)
colCount = dtData[0].ItemArray.Length;
FileInfo fi = new FileInfo(savePath);
if (!fi.Directory.Exists)
{
fi.Directory.Create();
}
FileStream fs = new FileStream(savePath, System.IO.FileMode.Create, System.IO.FileAccess.Write);
StreamWriter sw = new StreamWriter(fs, System.Text.Encoding.UTF8);
try
{
string data = string.Empty;
//title
for (int i = 0; i < colCount; i++)
{
data += dtData[0].Table.Columns[i].ColumnName.ToString();
if (i < colCount - 1)
{
data += ",";
}
}
sw.WriteLine(data);
//写出各行数据
for (int i = 0; i < dtData.Length; i++)
{
data = string.Empty;
for (int j = 0; j < colCount; j++)
{
string str = dtData[i][j].ToString();
str = str.Replace("\"", "\"\"");
if (str.Contains(',') || str.Contains('"')
|| str.Contains('\r') || str.Contains('\n'))
{
str = string.Format("\"{0}\"", str);
}

data += str;
if (j < colCount - 1)
{
data += ",";
}
}
sw.WriteLine(data);
}
}
catch (Exception ex)
{
// 错误日志
DLLogManager.WriteErrLog(MethodBase.GetCurrentMethod().Name, ex.message);
throw ex;
}
finally
{
sw.Close();
fs.Close();
}
}
}

 

 

/// <summary>
/// 导出CSV文件
/// </summary>
/// <param name="saveFileName">保存文件名</param>
/// <param name="dtData">数据</param>
/// <param name="exItems">导出项目列名</param>
public static void ExportCSVFileByItem(string saveFileName, DataRow[] dtData, string[] exItems)
{
if (dtData.Length > 0)
{
FileInfo fi = new FileInfo(savePath);
if (!fi.Directory.Exists)
{
fi.Directory.Create();
}
FileStream fs = new FileStream(savePath, System.IO.FileMode.Create, System.IO.FileAccess.Write);
StreamWriter sw = new StreamWriter(fs, System.Text.Encoding.UTF8);
try
{
string data = string.Empty;
//title
for (int i = 0; i < exItems.Length; i++)
{
data += exItems[i];
if (i < exItems.Length - 1)
{
data += ",";
}
}
sw.WriteLine(data);
//写出各行数据
for (int i = 0; i < dtData.Length; i++)
{
data = string.Empty;
for (int j = 0; j < exItems.Length; j++)
{
string str = dtData[i][exItems[j]].ToString();
str = str.Replace("\"", "\"\"");
if (str.Contains(',') || str.Contains('"')
|| str.Contains('\r') || str.Contains('\n'))
{
str = string.Format("\"{0}\"", str);
}

data += str;
if (j < exItems.Length - 1)
{
data += ",";
}
}
sw.WriteLine(data);
}
}
catch (Exception ex)
{
// 写错误日志
DLLogManager.WriteErrLog(MethodBase.GetCurrentMethod().Name, ex.Message);
throw ex;
}
finally
{
sw.Close();
fs.Close();
}
}
}