I am having trouble exporting my gridview to an excel file. Everything works except when I hit the export button, the data that is supposed to be exported to an excel file displays on the web page instead. I am suspecting that this is a problem with Response.ContentType and the file name that I specified. However, I already went through multiple documentations and examples and it doesn't seem like those two are the root problems in my case. Can Anyone help?
<asp:Button ID="btnExport" runat="server" Text="Export To MS Excel File" CssClass="btnMain" OnClick="btnExport_Click" />
Protected Sub btnExport_Click(ByVal sender As Object, ByVal e As System.EventArgs)
Dim filename As String = "PerformanceEval Status Report" & Date.Now.Year.ToString & "-" & _
formatNumberTo2Digits(DateTime.Now.Month) & "-" & formatNumberTo2Digits(DateTime.Now.Day) & ".xls"
With Page.Response
.Clear()
.Buffer = True
.AddHeader("content_disposition", "attachment;filename" & filename)
.Charset = ""
'--to open the Excel file without saving then comment out the line below
'.Cache.SetCacheability(HttpCacheability.NoCache)
'.ContentType = "application/vnd.xls" 'data appears on web page
'.ContentType = "application/vnd.ms-excel" 'try to download .aspx document NOT .xml
.ContentType = "application/ms-excel" 'data appears on web page
End With
Dim strWriter As New System.IO.StringWriter
Dim htmlWriter As System.Web.UI.HtmlTextWriter = New HtmlTextWriter(strWriter)
Dim gvexport As GridView = New GridView
gvexport.AutoGenerateColumns = False
gvexport.CssClass = "gridData"
gvexport.GridLines = GridLines.Horizontal
gvexport.HeaderStyle.CssClass = "gridHeader"
gvexport.RowStyle.CssClass = "gridRow"
gvexport.AlternatingRowStyle.CssClass = "gridRow_Alt"
gvexport.FooterStyle.CssClass = "gridFooter"
Dim dv As DataView = New DataView(Me.ds.Tables(0)) 'default is sorted by last name
'Dim dv As DataView = New DataView(Me.ds.Tables(0))
dv.RowFilter = GetFilter()
'-- add columns for report
addGVcolumn("Employee Name", "EmployeeName", gvexport, -1, HorizontalAlign.Left)
addGVcolumn("Employee ID", "SID", gvexport, -1, HorizontalAlign.Left)
addGVcolumn("Email", "WorkEmail", gvexport, -1, HorizontalAlign.Left)
addGVcolumn("StatusID", "StatusID", gvexport, 50, HorizontalAlign.Center)
gvexport.DataSource = dv
gvexport.DataBind()
gvexport.RenderControl(htmlWriter)
Response.Output.Write(strWriter.ToString())
Response.Flush()
Response.End()
Again, I am able to generate the content but is not able to make my data exports into excel. Thanks a lot!
You are giving the wrong header:
.AddHeader "content-disposition", "attachment; filename="& filename &";"
Related
I have a simple button event handler in ASP.NET that allows the user to download a spreadsheet to their browser and at the same time displays a set of controls relating to futher processing of that spreadsheet. The code is below:
Protected Sub btnDownLoadReview_Click(sender As Object, e As EventArgs) Handles btnDownLoadReview.Click
Dim excelEngine As ExcelEngine = New ExcelEngine()
Dim mboXLS() As Byte = Session("ScrubDataExcel")
Dim stream As Stream = New MemoryStream(mboXLS)
Dim workBookFinal As IWorkbook = excelEngine.Excel.Workbooks.Open(stream)
Dim fileName As String = UniqueFileName(".xls")
Dim sURL As String = ConfigurationManager.AppSettings("UploadFileName").ToString() & "_" & fileName
lblDoYouWishToModify.Visible = True
btnUploadCorrections.Visible = True
fupSelectFile.Visible = True
btnUploadCorrections.Visible = True
lblYouMayResubmit.Visible = True
workBookFinal.SaveAs(HttpContext.Current.Server.MapPath(sURL))
Response.ContentType = "application/xls"
Response.AppendHeader("Content-Disposition", "attachment; filename=" + sURL)
Response.TransmitFile(Server.MapPath(sURL))
Response.End()
End Sub
The problem seems to be the presence of the Reponse object invocations. If I remove these 4 lines, the controls display. If I refer to even one of them the controls do not display. No error is thrown but it seems as if the Visible property settings are ignored.
I tried moving the Visible settings to positions before and after the Reponse settings but to no avail.
Any ideas as to what could be wrong here?
Thanks
Carl
I have found good information on how to automatically download a file to the client advertised as a solution of how to print using code
(https://forums.asp.net/t/1233841.aspx?How+do+I+print+from+Reporting+Services+AUTOMATICALLY+in+VB+Net+web+app+)
but what I need to do is have the code print the document without the user interacting.
From what I have found it appears this can not be done as one might casually think. ReportViewer for example does not have a 'print' method.
The only two solutions appears to be to use ProcessStart (which then means saving the file to the file system before printing which I dont want to do)
or maybe (will be researching this today) create a subscription using code and then delete it later.
You are not able to print a report directly from your asp.net page. The reason for this is security. If it allowed you to send a file through the network and onto the clients computer, and then search the computer for a printer, this could cause major security issues. The report viewer does have a print icon, but this disappears when you deploy the project and run the page remotely. I have faced the same issue in the past and found it best to just export the report to say PDF and allow the user to Download it. I have used the below code to accomplish this task in the past:
Private Sub CreatePDFMatrix(fileName As String)
' ReportViewer1.LocalReport.DataSources.Clear()
Dim adapter As New ReportDataSetTableAdapters.vwPrintTagsTableAdapter
Dim table As New ReportDataSet.vwPrintTagsDataTable
Dim month = MonthName(Date.Today.Month)
Dim year = Date.Today.Year
Dim p(1) As ReportParameter
Dim warnings() As Warning
Dim streamIds As String()
Dim mimeType As String = String.Empty
Dim encoding As String = String.Empty
Dim extension As String = String.Empty
Dim adpt2 As New ReportDataSetTableAdapters.vwPrintTagsTableAdapter
adapter.FillForMainReport(table, DropDownList1.SelectedValue, g_Company, g_Division)
Me.ReportViewer1.LocalReport.DataSources.Add(New ReportDataSource("DataSet1", CType(table, DataTable))) 'Add(New ReportDataSource("ReportingData", CType(table, DataTable)))
Me.ReportViewer1.DataBind()
Dim viewer = ReportViewer1
viewer.ProcessingMode = ProcessingMode.Local
viewer.LocalReport.ReportPath = "Report1.rdlc"
p(0) = New ReportParameter("MonthYear", month & "-" & year)
Dim check = DropDownList1.SelectedValue
ReportViewer1.LocalReport.SetParameters(p(0))
p(1) = New ReportParameter("Location", DropDownList1.SelectedValue)
ReportViewer1.LocalReport.SetParameters(p(1))
Try
Dim bytes As Byte() = viewer.LocalReport.Render("PDF", Nothing, mimeType, encoding, ".pdf", streamIds, warnings)
Response.Buffer = True
Response.Clear()
Response.ContentType = mimeType
Response.AddHeader("content-disposition", Convert.ToString((Convert.ToString("attachment; filename=") & fileName) + ".") & extension)
Response.BinaryWrite(bytes)
' create the file
Response.Flush()
Catch ex As Exception
Debug.Print(ex.ToString)
End Try
End Sub
I have a webpage with an export button. Is it possible to export a sql table to excel when this button is pressed? I can do it with a gridview but would just like a simple button with code behind to do the work. Can someone point me in the direction I need?
Here is a utility function you can use:
Public Shared Sub ExportToSpreadsheet(table As DataTable, filename As String)
' Get a hold of the HTTP context and clear it, because we are going to push the CSV data through the context
Dim context = HttpContext.Current
context.Response.Clear()
' Loop through each column in your data table
For Each column As DataColumn In table.Columns
' Write column names
context.Response.Write(column.ColumnName + ";")
Next
context.Response.Write(Environment.NewLine)
' Loop through each row in the data table
For Each row As DataRow In table.Rows
' Loop through each column in row
For i As Integer = 0 To table.Columns.Count - 1
' Write each column value
context.Response.Write(row(i).ToString().Replace(";", [String].Empty) & ";")
Next
' Write a new line between rows of data
context.Response.Write(Environment.NewLine)
Next
' Set the content type and headers
context.Response.ContentType = "text/csv"
context.Response.AppendHeader("Content-Disposition", "attachment; filename=" & filename & ".csv")
context.Response.[End]()
End Sub
Then you can call it like this:
ExportToSpreadsheet(YourDataTable, "YourFileName")
Note: Since it is a Shared function, then you can put it in a utility class and do not need to instantiate (New) the class to use the function.
If you want it in excel you can use the following code. Select the data and put it in a Gridview and do the following.
Dim GridView1 As New GridView
SqlDataSource1.SelectCommand = "SELECT * FROM TableName"
GridView1.DataSource = SqlDataSource1
GridView1.DataBind()
Response.Clear()
Response.Buffer = True
Response.ContentType = "application/vnd.ms-excel"
Response.Charset = ""
Me.EnableViewState = False
Dim oStringWriter As New System.IO.StringWriter
Dim oHtmlTextWriter As New System.Web.UI.HtmlTextWriter(oStringWriter)
GridView1.RenderControl(oHtmlTextWriter)
Response.Write(oStringWriter.ToString())
Response.End()
You can also format the Gridview to make it look good on the Excel Sheet.
i want to read the metadata (such as author, keywords, etc.) of the Word, Excel file by asp.net (vb). How can I do that ?
is there any sample, reference site ?
i found the following code online, but it return error for the 2nd statement (" Dim excelbook As New Microsoft.Office.Interop.Excel.Workbook ")
Public Sub ReadExcel(ExcelFileName As String)
Dim Wapp As New Microsoft.Office.Interop.Excel.Application
Dim excelbook As New Microsoft.Office.Interop.Excel.Workbook
If Wapp Is Nothing Then
Wapp = New Microsoft.Office.Interop.Excel.Application
End If
If excelbook Is Nothing Then
excelbook = New Microsoft.Office.Interop.Excel.Workbook
Else
excelbook.Close()
End If
excelbook = Wapp.Workbooks.Open(ExcelFileName)
Dim _BuiltInProperties As Object = excelbook.BuiltinDocumentProperties
If Not _BuiltInProperties Is Nothing Then
excel_keyword = _BuiltInProperties("Keywords").Value
End If
If Not excelbook Is Nothing Then
excelbook.Close()
End If
If Not Wapp Is Nothing Then
Wapp.Quit()
End If
End Sub
here is the example for the same. Or you can download from https://dl.dropbox.com/u/79986486/StackOverFlow9684368.zip {Temporary}
You can use openXML with C# or VB.Net to achive this.
Hope this helps.
Quoting from Social.MSDN
You can access the values using DSOFile (works for a whole bunch of different fileTypes), or more simply, you can access these properties like this in VBA
Sub Macro1()
'
' Macro1 Macro
'
Dim mWorkbook As Workbook
Set mWorkbook = Application.Workbooks(1)
mWorkbook.BuiltinDocumentProperties("Author").Value = "the Author"
mWorkbook.BuiltinDocumentProperties("Title").Value = "the Title"
mWorkbook.BuiltinDocumentProperties("Subject").Value = "the Subject"
End Sub
I have a problem with FileUpload, when I select a file from the local machine, it will not bring the real path of the file, it will use the path for the project files and assume the file I am selecting is there, any ideas?
Example:
File name is "Q.JPG" and is in "C:\"
when I browse to "C:\" and select "Q.JPG" and click open, I get the following Error
Could not find file 'C:\Program Files\Microsoft Visual Studio 8\Common7\IDE\q.jpg'.
So when I fire up the code for Uploading the file to FTP for example, it will return an error because file doesn't exist
HTML side:
<asp:FileUpload ID="FU" runat="server" Height="24px" />
Below is the VB code:
Protected Sub btnUpload_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnUpload.Click
If FU.PostedFile IsNot Nothing AndAlso FU.PostedFile.FileName <> "" Then
Dim MaxSize As Integer = FU.PostedFile.ContentLength
If MaxSize > "2097152" Then
lblUpload.Text = "The file size cannot exceed 2 MB"
btnSave.Focus()
GoTo 99
End If
'--------------------------
' set up request...
Dim LocFile As String = FU.PostedFile.FileName
Dim clsRequest As System.Net.FtpWebRequest = DirectCast(System.Net.WebRequest.Create("ftp://myftp.com/" & LocFile), System.Net.FtpWebRequest)
clsRequest.Credentials = New System.Net.NetworkCredential("username", "password")
clsRequest.Method = System.Net.WebRequestMethods.Ftp.UploadFile
' read in file...
Dim bFile() As Byte = System.IO.File.ReadAllBytes(FU.PostedFile.FileName)
' upload file...
Dim clsStream As System.IO.Stream = clsRequest.GetRequestStream()
clsStream.Write(bFile, 0, bFile.Length)
clsStream.Close()
clsStream.Dispose()
'--------------------------
lblUpload.Text = "Uploaded"
btnSave.Focus()
Else
lblUpload.Text = "Choose a file to upload"
btnSave.Focus()
End If
99: 'Do Nothing
End Sub
The problem is you're trying to read in the PostedFile as a local file (on the web server), not from the HttpPostedFile object attached to the FileUploader.
Try:
Dim objFileStream As System.IO.Stream = FU.PostedFile.InputStream
Dim bFile(objFileStream.Length) As Byte
objFileStream.Read(bFile, 0, objFileStream.Length)
I tried something, and it worked..
FU.SaveAs("C:\" & FU.FileName)
'--------------------------
' set up request...
Dim LocFile As String = FU.PostedFile.FileName
Dim clsRequest As System.Net.FtpWebRequest = DirectCast(System.Net.WebRequest.Create("MyFTP.com" & LocFile), System.Net.FtpWebRequest)
clsRequest.Credentials = New System.Net.NetworkCredential("username", "password")
clsRequest.Method = System.Net.WebRequestMethods.Ftp.UploadFile
It worked.. simply saved the file from FU (FileUpload) to C:\ and then setting the address to always start at C:\