private void Export(string filePath) //filePath为保存到本地磁盘的位置
{
using (FileStream fs=new FileStream(filePath,FileMode.Create,FileAccess.Write))
{
StreamWriter sw = new StreamWriter(fs);
string col_txt = "";
string row_txt = "";
foreach (DataColumn item in dt.Columns) // dt 为DataTable 循环写入列标题
{
col_txt += item.ToString() + ",";
}
col_txt = col_txt.Substring(0, col_txt.Length - 1); //去掉最后多于的逗号
sw.WriteLine(col_txt);<span style="white-space:pre">//写入更改
foreach (DataRow item in dt.Rows)//循环写入行数据
{
row_txt = "";<span style="white-space:pre">//容易漏写,造成数据的重复写入
for (int i = 0; i < dt.Columns.Count; i++)
{
row_txt += item[i].ToString() + ",";
}
row_txt = row_txt.Substring(0, row_txt.Length - 1); //去掉最后多于的逗号
sw.WriteLine(row_txt);//写入更改
}
sw.Flush(); //此处必须有此操作
}
}
C# Winform实现数据的导出为txt或者CSV或者excel格式
最新推荐文章于 2024-09-05 15:04:58 发布