从DGV中导出至CSV格式中,中文出现乱码?
我有一支程式, 需从DataGridView中将数据导出至csv格式的文件的,在本地没有问题, 但是放到其他的电脑上,就会出现乱码, 是什么原因? 代码如下:
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using
namespace Statistic.BaseClass
{
class DataExport
{
public static void ExportToCSV(DataGridView dgv, string fileName)
{
if (dgv.Rows.Count < 1)
{
MessageBox.Show("没有记录!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
return;
}
string strFileName = Application.StartupPath + "\\" + fileName;
StreamWriter sw = new StreamWriter(strFileName, false, Encoding.UTF8);
string strLine = "";
foreach (DataGridViewColumn col in dgv.Columns)
{
if (col.Visible)
{
strLine += col.HeaderText.Trim() + ",";
}
}
strLine = strLine.Substring(0, strLine.Length - 1);
sw.WriteLine(strLine);
sw.Flush();
foreach (DataGridViewRow dgvr in dgv.Rows)
{
strLine = "";
foreach (DataGridViewCell dgvc in dgvr.Cells)
{
if (dgvc.Visible)
{
if (dgvc.Value == null)
{
strLine += " ,";
}
else
{
strLine += dgvc.Value.ToString().Trim() + ",";
}
}
}
sw.WriteLine(strLine);
sw.Flush();
}
sw.Close();
MessageBox.Show(string.Format("数据已成功导出至\n{0}\n文件中!", strFileName), "导出成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
}