如何轻松保存dataGridView为.xls或.csv,而不提示用户使用saveFileDialog c# Winfo
本文关键字:用户 提示 Winfo saveFileDialog dataGridView 保存 何轻松 xls csv | 更新日期: 2023-09-27 17:50:30
我正在做一个项目,该项目将允许用户在c# Winform dataGridView中查看MySQL数据库表。
我希望用户能够将dataGridView内容保存到c:'temp'export.xls,而不提示用户使用saveFileDialog(它使用saveFileDialog是很好的,只要它可以绕过任何用户输入并保存为c:'temp'export.xls),单击按钮。我需要帮助修改第二部分以绕过用户输入。
我用来保存数据的代码分为两部分(第二部分中的代码提示用户保存位置,但我想省略它并使其自动):
private void ToCsV(DataGridView dGV, string filename)
{
string stOutput = "";
// Export titles:
string sHeaders = "";
for (int j = 0; j < dGV.Columns.Count; j++)
sHeaders = sHeaders.ToString() + Convert.ToString(dGV.Columns[j].HeaderText) + "'t";
stOutput += sHeaders + "'r'n";
// Export data.
for (int i = 0; i < dGV.RowCount - 1; i++)
{
string stLine = "";
for (int j = 0; j < dGV.Rows[i].Cells.Count; j++)
stLine = stLine.ToString() + Convert.ToString(dGV.Rows[i].Cells[j].Value) + "'t";
stOutput += stLine + "'r'n";
}
Encoding utf16 = Encoding.GetEncoding(1254);
byte[] output = utf16.GetBytes(stOutput);
FileStream fs = new FileStream(filename, FileMode.Create);
BinaryWriter bw = new BinaryWriter(fs);
bw.Write(output, 0, output.Length); //write the encoded file
bw.Flush();
bw.Close();
fs.Close();
}
第2部分:
private void button4_Click(object sender, EventArgs e)
{
SaveFileDialog sfd = new SaveFileDialog();
sfd.Filter = "Excel Documents (*.xls)|*.xls";
sfd.FileName = "export.xls";
if (sfd.ShowDialog() == DialogResult.OK)
{
// ToCsV(dataGridView1, @"c:'temp'export.xls"); ???????
ToCsV(dataGridView1, sfd.FileName);
}
我想修改第二部分以自动保存@ c:'temp'export.xls。希望我已经很好地解释了我的意图。我已经研究了NPOI库,但不确定这是否是我需要的。这将是很好的在后台这样做的情况下,由于某种原因,用户没有安装excel。
为什么不这样做呢?或者如果你想在后台运行它,你可以在这里查看如何使用后台worker类,http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker(v=vs.110).aspx
private void button4_Click(object sender, EventArgs e)
{
//I would probabaly generate a time stamped Filename so not to over write existing files
// You can use something like a background worker to run this in the back ground
ToCsV(dataGridView1, @"c:'temp'export.xls");
}