保存文件对话框并导出到 Excel 工作表
Posted
技术标签:
【中文标题】保存文件对话框并导出到 Excel 工作表【英文标题】:Save file dialog and export to Excel sheet 【发布时间】:2011-03-07 09:57:12 【问题描述】:我有一个数据网格视图,并且已导出到 Excel 工作表。代码运行良好,但是当 Save As 对话框出现并保存文件时,我找不到该文件,也没有出现错误。
我的代码
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();
【问题讨论】:
【参考方案1】:当你打电话时
saveFileDialog.ShowDialog()
它返回一个 DialogResult 而不是选定的文件名。 SaveCopyAs 方法需要一个文件名。
查看 SaveFileDialog here 的教程,了解如何获取选定的文件名。它应该是这样的:
private void Form1_DoubleClick(object sender, System.EventArgs e)
if( this.saveFileDialog1.ShowDialog() == DialogResult.OK )
MessageBox.Show("The Save button was clicked or the Enter key was pressed" +
"\nThe file would have been saved as " +
this.saveFileDialog1.FileName);
else
MessageBox.Show("The Cancel button was clicked or Esc was pressed");
【讨论】:
以上是关于保存文件对话框并导出到 Excel 工作表的主要内容,如果未能解决你的问题,请参考以下文章