请问谁有C#datagridview导出csv格式的excel的代码啊,发一下学习学习?

在winform中点击导出就直接导出到excel的那种!

第1个回答  2011-07-26
//我从网上下载了这段代码
//这段代码的主要意思是 判断导出文件是否已经存在,如果文件已经存在就删除掉
// 打开文件 StreamWriter sw = new StreamWriter(new FileStream(strPath, ileMode.CreateNew), Encoding.GetEncoding("GB2312"));
把字段名写入了文件
//二层循环写入数据
//注意字段的间隔符是 ","
//关闭文件 这样就可以
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Data;

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

sw.Close();
}
catch (Exception ex)
{
throw ex;
}
System.Diagnostics.Process.Start(strPath);
}
}
}
相似回答
大家正在搜