Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Save file dialog and export to Excel sheet

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();
    }
}
like image 506
Myworld Avatar asked Mar 07 '11 09:03

Myworld


1 Answers

When you call

saveFileDialog.ShowDialog()

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:

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");
}
like image 109
TurBas Avatar answered Oct 03 '22 14:10

TurBas