Search code examples
c#asp.netinteropexcel-interopsave-as

How to save created excel instance to client's disk with save as dialog box


In a project when user click a button, some data is gotten and written to an excel instance by interop library.

Now, I want that: When excel instance get all data, a save as dialog box muste be open and save this excel instance to user specified path.

Is there a way to do it?

Edit:

My code to get data to excel is here:

Public Sub ExportToExcel(ByVal dt As DataTable, ByVal outputPath As String)
    ' Create the Excel Application object
    Dim excelApp As New Microsoft.Office.Interop.Excel.ApplicationClass

    ' Create a new Excel Workbook
    Dim excelWorkbook As Excel.Workbook = excelApp.Workbooks.Add(Type.Missing)

    Dim excelSheet As Excel.Worksheet = excelWorkbook.Worksheets(1)
    excelApp.Visible = True
    ' Copy each DataTable as a new Sheet
    'sheetIndex += 1

    '' Create a new Sheet
    'excelSheet = CType( _
    '    excelWorkbook.Sheets.Add(excelWorkbook.Sheets(sheetIndex), _
    '    Type.Missing, 1, Microsoft.Office.Interop.Excel.XlSheetType.xlWorksheet), Microsoft.Office.Interop.Excel.Worksheet)

    excelSheet.Name = "Bayi"

    ' Copy the column names (cell-by-cell)
    For col = 0 To dt.Columns.Count - 1
        excelSheet.Cells(1, col + 1) = dt.Columns(col).ColumnName
    Next

    CType(excelSheet.Rows(1, Type.Missing), Microsoft.Office.Interop.Excel.Range).Font.Bold = True

    ' Copy the values (cell-by-cell)
    For col = 0 To dt.Columns.Count - 1
        For row = 0 To dt.Rows.Count - 1
            excelSheet.Cells(row + 2, col + 1) = dt.Rows(row).ItemArray(col)
        Next
    Next

    excelSheet = Nothing

    ' Save and Close the Workbook
    excelWorkbook.SaveAs(outputPath, Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookNormal, Type.Missing, _
     Type.Missing, Type.Missing, Type.Missing, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive, _
     Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing)

    excelWorkbook.Close(True, Type.Missing, Type.Missing)

    excelWorkbook = Nothing

    ' Release the Application object
    excelApp.Quit()
    excelApp = Nothing

    ' Collect the unreferenced objects
    GC.Collect()
    GC.WaitForPendingFinalizers()

End Sub

Solution

  • I am not sure, that this is what you want, but if you want to let a user download an excel file, that you've created on the server side, then just write the content of the excel file to the Response, set the correct mime type - and there you go! P.S. Don't forget to clear the currently generated response.