2014-09-04 16 views
1

我已經編寫了將數據導出到xlsx文件的代碼。但我不明白如何顯示窗口提示下載該客戶端的xlsx文件。 這裏是我的代碼:如何顯示窗口提示下載excel文件?

Private Sub DataTableToExcel(ByVal tbl As DataTable) 
    Dim Excel As Object = CreateObject("Excel.Application") 
    Dim strFilename As String 
    Dim intCol, intRow As Integer 
    Dim strPath As String = "C:\" 


    If Excel Is Nothing Then 
     MsgBox("It appears that Excel is not installed on this machine. This operation requires MS Excel to be installed on this machine.", MsgBoxStyle.Critical) 
     Return 
    End If 
    Try 
     With Excel 
      .SheetsInNewWorkbook = 1 
      .Workbooks.Add() 
      .Worksheets(1).Select() 

      .cells(1, 1).value = "Complaint Detail Report" 'Heading of the excel file 
      .cells(1, 1).EntireRow.Font.Bold = True 


      Dim intI As Integer = 1 
      For intCol = 0 To tbl.Columns.Count - 1 
       .cells(2, intI).value = tbl.Columns(intCol).ColumnName 
       .cells(2, intI).EntireRow.Font.Bold = True 
       intI += 1 
      Next 
      intI = 3 
      Dim intK As Integer = 1 
      For intCol = 0 To tbl.Columns.Count - 1 
       intI = 3 
       For intRow = 0 To tbl.Rows.Count - 1 
        .Cells(intI, intK).Value = tbl.Rows(intRow).ItemArray(intCol) 
        intI += 1 
       Next 
       intK += 1 
      Next 
      If Mid$(strPath, strPath.Length, 1) <> "\" Then 
       strPath = strPath & "\" 
      End If 
      strFilename = strPath & "ComplaintDetail.xlsx" 
      .ActiveCell.Worksheet.SaveAs(strFilename) 
     End With 
     System.Runtime.InteropServices.Marshal.ReleaseComObject(Excel) 
     Excel = Nothing 
     MsgBox("Data's are exported to Excel Succesfully: Location: '" & strFilename & "'", MsgBoxStyle.Information) 
     ' Response.AddHeader("content-disposition", "attachment;filename=ComplaintDetail.xlsx") 
     'Response.ContentType = "application/vnd.excel" 
    Catch ex As Exception 
     MsgBox(ex.Message) 
    End Try 
    Dim pro() As Process = System.Diagnostics.Process.GetProcessesByName("EXCEL") 
    For Each i As Process In pro 
     i.Kill() 
    Next 

End Sub 

在這裏,我保存.xlsx文件,直接到「C驅動器」。 爲什麼我選擇C Drive? :因爲99%的人有C:在那兒有電腦。 但我得到了一些情況,用戶不允許訪問他們的C驅動器,或者他們不允許在C驅動器內寫入任何內容。 這就是爲什麼我試圖添加此窗口提示,其中用戶將決定在哪裏保存該文件。但是我在上面的代碼中遇到了一些問題。 你能幫我在上面的代碼中添加窗口提示嗎?

+0

你爲什麼要放一個C#標籤? – Gab 2014-09-04 05:59:04

+0

使用臨時文件%tmp% – 2014-09-04 06:01:13

+0

它是一個Windows應用程序嗎?如果是,那麼你不應該用asp.net標記它。 – Priyank 2014-09-04 06:04:43

回答

-1

嘗試使用類似保存文件對話框(可以通過UI設計器添加)。 然後使用:

If dialog.Show() = Windows.Forms.DialogResult.OK Then 
    strPath = dialog.FileName 
End If 
+0

你可以做這通過網絡... – Codexer 2014-09-04 06:37:55

0
  1. 保存在App_Data目錄。您可以使用Server.MapPath("~/App_Data")找到絕對路徑此路徑可由應用程序寫入
  2. 使用Response.TransmitFile可以使文件被下載。