简体   繁体   English

保存文件对话框并导出到Excel工作表

[英]Save file dialog and export to Excel sheet

I had a datagrid view, and I had exported to an Excel sheet. 我有一个数据网格视图,我已导出到Excel工作表。 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();
    }
}

When you call 你打电话的时候

saveFileDialog.ShowDialog()

it returns a DialogResult and not the selected filename. 它返回一个DialogResult而不是选定的文件名。 The SaveCopyAs method expects a filename. SaveCopyAs方法需要一个文件名。

Check a tutorial of SaveFileDialog here to see how to get the selected filename. 在这里查看SaveFileDialog教程,了解如何获取所选文件名。 It should be something like: 它应该是这样的:

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");
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM