在 C# 中将 DataGridView 数据导出为 CSV
在此代码示例中,我们将学习如何使用 C# 代码将 DataGridView 数据导出到 CSV 文件并将其保存在文件夹中。
在这个程序中,首先,我们必须连接到数据库并从中获取数据。然后,我们将在数据网格视图中显示该数据,如下图所示。
让我们转到页面加载事件,获取员工数据,并绑定数据 GridView。
private void FrmExport_Load(object sender, EventArgs e)
{
SqlConnection sqlCon;
string conString = null;
string sqlQuery = null;
conString = "Data Source=.;Initial Catalog=DemoTest;Integrated Security=SSPI;";
sqlCon = new SqlConnection(conString);
sqlCon.Open();
sqlQuery = "SELECT * FROM tblEmployee";
SqlDataAdapter dscmd = new SqlDataAdapter(sqlQuery, sqlCon);
DataTable dtData = new DataTable();
dscmd.Fill(dtData);
dataGridView1.DataSource = dtData;
}
然后,在按钮单击事件处理程序上,编写以下代码。
private void btnCsv_Click(object sender, EventArgs e)
{
if (dataGridView1.Rows.Count > 0)
{
SaveFileDialog sfd = new SaveFileDialog();
sfd.Filter = "CSV (*.csv)|*.csv";
sfd.FileName = "Output.csv";
bool fileError = false;
if (sfd.ShowDialog() == DialogResult.OK)
{
if (File.Exists(sfd.FileName))
{
try
{
File.Delete(sfd.FileName);
}
catch (IOException ex)
{
fileError = true;
MessageBox.Show("It wasn't possible to write the data to the disk." + ex.Message);
}
}
if (!fileError)
{
try
{
int columnCount = dataGridView1.Columns.Count;
string columnNames = "";
string[] outputCsv = new string[dataGridView1.Rows.Count + 1];
for (int i = 0; i < columnCount; i++)
{
columnNames += dataGridView1.Columns[i].HeaderText.ToString() + ",";
}
outputCsv[0] += columnNames;
for (int i = 1; (i - 1) < dataGridView1.Rows.Count; i++)
{
for (int j = 0; j < columnCount; j++)
{
outputCsv[i] += dataGridView1.Rows[i - 1].Cells[j].Value.ToString() + ",";
}
}
File.WriteAllLines(sfd.FileName, outputCsv, Encoding.UTF8);
MessageBox.Show("Data Exported Successfully !!!", "Info");
}
catch(Exception ex)
{
MessageBox.Show("Error :" + ex.Message);
}
}
}
}
else
{
MessageBox.Show("No Record To Export !!!", "Info");
}
}
现在,运行应用程序。点击“导出为 CSV”按钮时,它会询问文件保存位置。输入文件名,然后点击“确定”。它会生成一个 CSV 文件。
希望这段代码能帮助到所有读者。祝您编码愉快!
如果您喜欢此文章,请收藏、点赞、评论,谢谢,祝您快乐每一天。