您的位置:首页 > 其它

导出为CSV文件的类

2010-05-24 15:34 49 查看
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Data;

namespace Utility
{
public class CSVHelper
{
//导出为svc文件,strFileName为要导出的csv格式文件的路径和文件名:比如,"d:/test/test.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(dr[i].ToString());
strValue.Append(",");
}
strValue.Remove(strValue.Length - 1, 1);//移出掉最后一个,字符
sw.WriteLine(strValue);
}

sw.Close();
}
catch (Exception ex)
{
throw ex;
}
System.Diagnostics.Process.Start(strPath);
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: