C# 一些代码小结--datGirdView 保存到csv文件
2021-06-10 20:05
标签:file headers try creat 文件 too available err replace C# 一些代码小结--datGirdView 保存到csv文件 标签:file headers try creat 文件 too available err replace 原文地址:https://www.cnblogs.com/memorypro/p/10589003.html if (dataGridView1.Rows.Count == 0)
{
MessageBox.Show("No data available!", "Prompt", MessageBoxButtons.OK, MessageBoxIcon.Information);
return;
}
else
{
SaveFileDialog saveFileDialog = new SaveFileDialog();
saveFileDialog.Filter = "CSV files (*.csv)|*.csv";
saveFileDialog.FilterIndex = 0;
saveFileDialog.RestoreDirectory = true;
saveFileDialog.CreatePrompt = true;
saveFileDialog.FileName = null;
saveFileDialog.Title = "Save path of the file to be exported";
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
Stream myStream = saveFileDialog.OpenFile();
StreamWriter sw = new StreamWriter(myStream, System.Text.Encoding.GetEncoding(-0));
string strLine = "";
try
{
//Write in the headers of the columns.
for (int i = 0; i 0)
strLine += ",";
strLine += dataGridView1.Columns[i].HeaderText;
}
strLine.Remove(strLine.Length - 1);
sw.WriteLine(strLine);
strLine = "";
//Write in the content of the columns.
for (int j = 0; j 0)
strLine += ",";
if (dataGridView1.Rows[j].Cells[k].Value == null)
strLine += "";
else
{
string m = dataGridView1.Rows[j].Cells[k].Value.ToString().Trim();
strLine += m.Replace(",", ",");
}
}
strLine.Remove(strLine.Length - 1);
sw.WriteLine(strLine);
//Update the Progess Bar.
// toolStripProgressBar1.Value = 100 * (j + 1) / dataGridView1.Rows.Count;
}
sw.Close();
myStream.Close();
MessageBox.Show("Data has been exported to:" + saveFileDialog.FileName.ToString(), "Exporting Completed", MessageBoxButtons.OK, MessageBoxIcon.Information);
// toolStripProgressBar1.Value = 0;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Exporting Error", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
}
文章标题:C# 一些代码小结--datGirdView 保存到csv文件
文章链接:http://soscw.com/index.php/essay/93298.html