如何使用另存为对话框将创建的excel实例保存到客户端磁盘

时间:2010-12-22 13:40:36

标签: c# asp.net interop excel-interop save-as

在用户单击按钮的项目中,某些数据被interop库获取并写入excel实例。

现在,我希望:当excel实例获取所有数据时,将打开另存为对话框并将此excel实例保存到用户指定的路径。

有办法吗?

编辑:

我的数据获取excel的代码在这里:

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

2 个答案:

答案 0 :(得分:1)

如果您尝试从网络服务器将其添加到客户端,则不会出现这种情况。无需让您在客户端或类似的东西上安装闪存/ silverlight,超越浏览器客户端软件的安全性。

<强>更新 她是“A quick look at Silverlight 3: Save File Dialog” 并How to read and write files in JavaScript

答案 1 :(得分:1)

我不确定,这是你想要的,但如果你想让用户下载你在服务器端创建的excel文件,那么只需将excel文件的内容写入Response ,设置正确的mime类型 - 然后你去! 附:不要忘记清除当前生成的响应。