保存文件对话框并导出到 Excel 工作表
我有一个数据网格视图,并且已导出到 Excel 工作表。该代码运行良好,但是当“另存为”对话框出现并保存文件时,我找不到该文件,也没有出现错误。
我的代码
private void button1_Click(object sender, EventArgs e)
{
try
{
using (new ExcelUILanguageHelper())
{
SaveFileDialog saveFileDialog = new SaveFileDialog();
saveFileDialog.Filter = "Execl files (*.xls)|*.xls";
saveFileDialog.FilterIndex = 0;
saveFileDialog.RestoreDirectory = true;
saveFileDialog.CreatePrompt = true;
saveFileDialog.Title = "Export Excel File To";
Excel.ApplicationClass ExcelApp = new Excel.ApplicationClass();
ExcelApp.Application.Workbooks.Add(Type.Missing);
ExcelApp.Columns.ColumnWidth = 30;
for (int i = 0; i < DGData.Rows.Count; i++)
{
DataGridViewRow row = DGData.Rows[i];
for (int j = 0; j < row.Cells.Count; j++)
{
ExcelApp.Cells[i + 1, j + 1] = row.Cells[j].ToString();
}
}
ExcelApp.ActiveWorkbook.SaveCopyAs(saveFileDialog.ShowDialog());
ExcelApp.ActiveWorkbook.Saved = true;
ExcelApp.Quit();
}
}
catch (Exception ex)
{
MessageBox.Show("Cancelled Operation");
this.Close();
}
}
I had a datagrid view, and I had exported to an Excel sheet. The code worked well, but when the Save As dialog appeared and saved the file I could not find the file and no error appeared.
My code
private void button1_Click(object sender, EventArgs e)
{
try
{
using (new ExcelUILanguageHelper())
{
SaveFileDialog saveFileDialog = new SaveFileDialog();
saveFileDialog.Filter = "Execl files (*.xls)|*.xls";
saveFileDialog.FilterIndex = 0;
saveFileDialog.RestoreDirectory = true;
saveFileDialog.CreatePrompt = true;
saveFileDialog.Title = "Export Excel File To";
Excel.ApplicationClass ExcelApp = new Excel.ApplicationClass();
ExcelApp.Application.Workbooks.Add(Type.Missing);
ExcelApp.Columns.ColumnWidth = 30;
for (int i = 0; i < DGData.Rows.Count; i++)
{
DataGridViewRow row = DGData.Rows[i];
for (int j = 0; j < row.Cells.Count; j++)
{
ExcelApp.Cells[i + 1, j + 1] = row.Cells[j].ToString();
}
}
ExcelApp.ActiveWorkbook.SaveCopyAs(saveFileDialog.ShowDialog());
ExcelApp.ActiveWorkbook.Saved = true;
ExcelApp.Quit();
}
}
catch (Exception ex)
{
MessageBox.Show("Cancelled Operation");
this.Close();
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
当您调用时,
它返回 DialogResult 而不是选定的文件名。 SaveCopyAs 方法需要一个文件名。
此处查看 SaveFileDialog 教程,了解如何获取所选文件名。它应该是这样的:
When you call
it returns a DialogResult and not the selected filename. The SaveCopyAs method expects a filename.
Check a tutorial of SaveFileDialog here to see how to get the selected filename. It should be something like: