We have an ASP.NET 1.1 application that uses Crystal Reports to spit out an excel spreadsheet. The codes works under IIS6 but when we try to migrate it to IIS7 it is spitting out html with no content instead of the Excel file.
The MIME Type exists. Below is the code we are using. I did not write this code as I'm working primarily in 3.5 framework now. My assumption is I am missing something in the IIS7 configuration not the code since it works on IIS6. The rest of the ASP.NET 1.1 application works on IIS7.
Dim cr As ReportClass
'EXPORT the report based on the export type passed in.
Dim ExpOptions As New ExportOptions
Dim ContentType As String
Dim strExt As String
Trace.Write("DisplayReport reportname=" + ReportName + " SQL=" + SQL + " SQLSub1=" + Convert.ToString(Session("SQLSub1")))
'Get the report filled with the data.
If Session("SQLSub1") <> "" Then
If Not Session("SubRptName") Is Nothing Then
cr = PopulateReport(GetReportObject(ReportName), SQL, Session("SQLSub1"), Session("SubRptName"))
Session("SQLSub1") = ""
Session("SubRptName") = Nothing
Else
cr = PopulateReport(GetReportObject(ReportName), SQL, Session("SQLSub1"))
Session("SQLSub1") = ""
End If
Else
cr = PopulateReport(GetReportObject(ReportName), SQL)
End If
If DisplayType = ReportType.Excel Then
If ReportName.ToUpper = "ACTION" Or ReportName.ToUpper = "INVENTORY_EXCEL" _
Or ReportName.ToUpper = "UNDERPERFORM" Or ReportName.ToUpper = "EMPLOYEE_EXCEL" Then
Dim excelFormatOpts As New ExcelFormatOptions
' Set the excel format options.
excelFormatOpts.ExcelTabHasColumnHeadings = True
excelFormatOpts.ExcelUseConstantColumnWidth = False
ExpOptions.FormatOptions = excelFormatOpts
Else
ExpOptions.FormatOptions = New ExcelFormatOptions
End If
ExpOptions.ExportFormatType = ExportFormatType.Excel
ContentType = "application/vnd.ms-excel"
strExt = ".xls"
ElseIf DisplayType = ReportType.PDF Then
ExpOptions.ExportFormatType = ExportFormatType.PortableDocFormat
ExpOptions.FormatOptions = New PdfRtfWordFormatOptions
ContentType = "application/pdf"
strExt = ".pdf"
End If
'Stream the report to the screen
Dim req As New ExportRequestContext
req.ExportInfo = ExpOptions
Dim s As Stream
Try
s = cr.FormatEngine.ExportToStream(req)
Catch ex As Exception
Trace.Warn("DisplayReport cr.FormatEngine.ExportToStream(req) failed: " + ex.Message)
Dim x As String = String.Empty
End Try
Response.Clear()
'Response.ClearHeaders()
'Response.ClearContent()
Response.Buffer = True
Response.ContentType = ContentType
Response.AddHeader("Content-Type", ContentType)
Dim buffer(s.Length) As Byte
s.Read(buffer, 0, Int(s.Length))
Response.BinaryWrite(buffer)
Dim strContentDisposition As String = "inline;filename=" & ReportName.ToString.ToLower & strExt.ToString
Trace.Write("DisplayReport strContentDisposition=" + strContentDisposition)
Response.AddHeader("Content-Disposition", strContentDisposition)
Response.Cache.SetMaxAge(New TimeSpan(0, 0, 10))
Response.End()
Asked some devs here at work, this is what I got so far:
"Never seen that before, I’ve never even used the export to stream option in crystal before. However, if I were to guess, I would look at server permissions as a possible fault. I’ve seen situations where the user has to have special privileges to access streams."
Related
I have a method which is use to extract excel by copying it to a response and downloading it to the browser. Everything checks out fine apart from the two formatting issues which are encountered.
1 . You see i have some values which are defined like '10-2', the problem is that excel is treating it like a date(which should not happen).
2 . All the Zeroes in the column are disappearing.
I presume changing the column to a text type might resolve the issue but i cant seem to figure out how to do it.
Would be a great help if someone can help me with this.
The code i am using is below:
Dim name As String = "SweepstakesReport_" & RewardCodeForName & "_" & DateTime.Now.ToString("yyyyMMdd")
Dim tmp As String = ""
Dim tmptime As String = ""
Dim ExcelFile As String = ""
Dim stwWriter As System.IO.StringWriter = New System.IO.StringWriter
Dim htwWriter As System.Web.UI.HtmlTextWriter = New System.Web.UI.HtmlTextWriter(stwWriter)
Dim dgGrid As DataGrid = New DataGrid
Dim ds As New DataSet
ds = Session("dsRedeemed")
dgGrid.DataSource = ds.Tables(0).DefaultView
dgGrid.HeaderStyle.Font.Bold = True
dgGrid.DataBind()
dgGrid.RenderControl(htwWriter)
ExcelFile = name & ".xls"
Response.Clear()
Response.AddHeader("content-disposition", String.Format("attachment; filename={0}", ExcelFile))
'Response.ContentType = "application/ms-excel"
Response.ContentType = "application/octet-stream"
'Response.ContentEncoding = System.Text.Encoding.Unicode
'Response.BinaryWrite(System.Text.Encoding.Unicode.GetPreamble())
'Response.ContentType = "application/octet-stream"
Response.Write(stwWriter.ToString)
Response.End()
Thanks,
Haris.
I have 78 excel columns and I have 5 datagridviews.
How do I make connection?
I understand what you want to achieve, but to get the maximum out of any answer, it would be better if you add some code or some further explanation.
For example how should anyone know which excel data should be displayed in DataGridView one, two etc...
Anyway, i would recommend that you divide the task into two steps:
ReadExcel and DisplayData. In my opinion reading data from excel file via OLEDB is a good way to start. Therefore i recommend reading the following article: http://www.codeproject.com/Tips/705470/Read-and-Write-Excel-Documents-Using-OLEDB
For displaying the data in a DataGridView you need to bind a dataset to it. Maybe you´ll find the following post helpful:
How to bind Dataset to DataGridView in windows application
Its both c# code, but i think getting things running for vb.net is an easy task.
Edit: I found some older vb.net of mine you can use. It´s not that good piece of code but it should get you started. It imports the whole data of an excel sheet. But please don´t just copy and run :)
Public Shared Function ImportExcelSheetData(ByVal ExcelFilePath As String, _
ByVal SourceExcelSheetName As String, _
ByRef pDestDataTable As DataTable, _
ByRef ErrMsg As String, _
Optional ByVal WithHeader As Boolean = False) As Integer
Dim ConnectionString As String = ""
Dim WithHeaderString As String = ""
Dim nOutputRow As Integer = 0
Dim oleExcelCommand As OleDbCommand
Dim oleExcelConnection As OleDbConnection
ImportExcelSheetData = -1 ' Error by default
If System.IO.File.Exists(ExcelFilePath) <> True Then
ErrMsg = "Error: File does not exist." + vbCrLf + "Filepath: " + ExcelFilePath
Exit Function
End If
If WithHeader = True Then
WithHeaderString = "Yes"
Else
WithHeaderString = "No"
End If
ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + ExcelFilePath + ";Extended Properties=""Excel 12.0;HDR=" + WithHeaderString + ";IMEX=1"""
oleExcelConnection = New OleDbConnection(ConnectionString)
oleExcelConnection.Open()
If IsNothing(pDestDataTable) = True Then
pDestDataTable = New DataTable
End If
' if SourceExcelSheetName is not set, use first sheet!
If SourceExcelSheetName.Trim = "" Then
Dim tmpDataTable As DataTable = oleExcelConnection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, Nothing)
if IsNothing(tmpDataTable) OR tmpDataTable.Rows.Count < 1 Then
throw new Exception("Error: Could not determine the name of the first worksheet.")
End If
Dim firstSheetName As String = tmpDataTable.Rows(0)("TABLE_NAME").ToString()
If firstSheetName.Trim() <> "" then
SourceExcelSheetName = firstSheetName
End If
End If
If SourceExcelSheetName <> "" Then
Try
Dim oleAdapter As New OleDbDataAdapter()
oleExcelCommand = oleExcelConnection.CreateCommand()
If SourceExcelSheetName.EndsWith ("$") = True Then
oleExcelCommand.CommandText = "Select * From [" & SourceExcelSheetName & "]"
Else
oleExcelCommand.CommandText = "Select * From [" & SourceExcelSheetName & "$]"
End If
oleExcelCommand.CommandType = CommandType.Text
oleAdapter.SelectCommand = oleExcelCommand
oleAdapter.Fill(pDestDataTable)
oleExcelConnection.Close()
Catch ex As Exception
ErrMsg = Err.Description
Exit Function
End Try
End If
ImportExcelSheetData = 0 ' Ok
End Function
On the button click in my web page i run an sql statement, I also want to run a web request. I do not want to load anything from the web request, jsut run it. but here is the funny thing. The code that is the sql statement runs jsut fine, and then everything else below it just seems to not run.... at all. the server never receives the web request.
if i copy the code to a page and run just the web request code it works. but here it does not.
asp.net. thanks everyone. im stumped.
Imports System
Imports System.Data
Imports System.Web
Imports System.Data.SqlClient
Imports System.IO
Imports System.Net
Imports System.Text
Partial Class _Default
Inherits System.Web.UI.Page
Protected Sub btnAddDeckSize_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnAddDeckSize.Click
If txtDeckSize.Text > "" And txtNewDeckPrice.Text > "" Then
Dim WasError As Boolean = False
Dim SQLstring As String = "Server=server;Database=SecondLifeDatabases;Integrated Security=true"
Dim SQLconn As SqlConnection
Dim SQLcmd As New SqlCommand()
SQLconn = New SqlConnection(SQLstring)
Try
SQLconn.Open()
SQLcmd.Connection = SQLconn
Try
SQLcmd.CommandText = ("INSERT INTO [SecondLifeDatabases].[dbo].[YuGiOh-DecksAndPrices]([DeckSize] ,[PriceInLindins])VALUES (" + txtDeckSize.Text + "," + txtNewDeckPrice.Text + ")")
SQLcmd.ExecuteNonQuery()
Catch ex As Exception
Context.Response.Write("error:" + vbCrLf + " " + vbCrLf + "Unable to insert sql data, Type:" + vbCrLf + " " + vbCrLf + ex.Message)
WasError = True
SQLconn.Close()
End Try
Catch ex As Exception
Context.Response.Write("error:" + vbCrLf + " " + vbCrLf + "Could not open database:" + vbCrLf + " " + vbCrLf + ex.Message)
WasError = True
SQLconn.Close()
End Try
SQLconn.Close()
If WasError = False Then
Context.Response.Redirect("~/YuGiOh.aspx")
End If
Else
Context.Response.Write("Please check your values, something is Missing")
End If
'START OF WHERE CODE SEEMS TO NOT RUN
'THIS CODE ALONE RUNS ON ANOTHER PAGE
'BUT HERE, EVEN THO THE CODE ABOVE RUNS,
'I NEVER SEE ANY RESULTS FROM THE CODE BLOW
' Create a request using a URL that can receive a post.
Dim request As WebRequest = WebRequest.Create("http://sim6103.agni.lindenlab.com:12046/cap/b936c974-cfab-c2ee-a184-4288fe0a10f8")
' Set the Method property of the request to POST.
request.Method = "POST"
' Create POST data and convert it to a byte array.
Dim postData As String = "This is a test that posts this string to a Web server."
Dim byteArray As Byte() = Encoding.UTF8.GetBytes(postData)
' Set the ContentType property of the WebRequest.
request.ContentType = "application/x-www-form-urlencoded"
' Set the ContentLength property of the WebRequest.
request.ContentLength = byteArray.Length
' Get the request stream.
Dim dataStream As Stream = request.GetRequestStream()
' Write the data to the request stream.
dataStream.Write(byteArray, 0, byteArray.Length)
' Close the Stream object.
dataStream.Close()
' Get the response.
Dim response As WebResponse = request.GetResponse()
' Display the status.
Console.WriteLine(CType(response, HttpWebResponse).StatusDescription)
' Get the stream containing content returned by the server.
dataStream = response.GetResponseStream()
' Open the stream using a StreamReader for easy access.
Dim reader As New StreamReader(dataStream)
' Read the content.
Dim responseFromServer As String = reader.ReadToEnd()
' Display the content.
Console.WriteLine(responseFromServer)
' Clean up the streams.
reader.Close()
dataStream.Close()
response.Close()
End Sub
I have created a windows application using list.asmx (getlistitems method) to download documents from a document library which is on another server. I am able to access document names, url, etc. When I use following code to download a file, it is returning html of the login page as content of each file that I am trying to download.
Any thoughts?
Dim spAuthentication As New Authentication()
spAuthentication.Url = authenticationWSAddress
spAuthentication.CookieContainer = New CookieContainer()
Dim spLists As New Lists()
spLists.Url = listWSAddress
'Try to login to SharePoint site with Form based authentication
Dim loginResult As LoginResult = spAuthentication.Login(userName, password)
Dim cookie As New Cookie()
'If login is successfull
If loginResult.ErrorCode = LoginErrorCode.NoError Then
'Get the cookie collection from the authenticatin web service
Dim cookies As CookieCollection = spAuthentication.CookieContainer.GetCookies(New Uri(spAuthentication.Url))
'Get the specific cookie which contains the security token
cookie = cookies(loginResult.CookieName)
'Initialize the cookie container of the list web service
spLists.CookieContainer = New CookieContainer()
'set the cookie of list web service to the authenticatio cookie
spLists.CookieContainer.Add(cookie)
'Dim responseNode As XmlNode = spLists.GetListCollection()
'response = responseNode.InnerXml
Dim query As String = "<mylistitems><Query><Where><Eq><FieldRef Name='FileDirRef' /><Value Type='Url'>DocLib/Property Documents/BELASERA AT FULTON (lax10027)/Master Meter Invoices</Value></Eq></Where></Query><QueryOptions><ViewAttributes Scope='RecursiveAll' IncludeRootFolder='False' /><IncludeAttachmentUrls>TRUE</IncludeAttachmentUrls><ViewFields><FieldRef Name='EncodedAbsUrl'/></ViewFields></QueryOptions></mylistitems>"
Dim doc As New XmlDocument()
doc.LoadXml(query)
Dim dt As DataTable = Nothing
Dim queryNode As XmlNode = doc.SelectSingleNode("//Query")
Dim viewNode As XmlNode = doc.SelectSingleNode("//ViewFields")
Dim optionNode As XmlNode = doc.SelectSingleNode("//QueryOptions")
Dim retNode As XmlNode = spLists.GetListItems("DocLib", String.Empty, queryNode, viewNode, String.Empty, optionNode, Nothing)
Dim ds As New DataSet()
Using sr As New StringReader(retNode.OuterXml)
ds.ReadXml(sr)
End Using
If ds.Tables("Row") IsNot Nothing AndAlso ds.Tables("Row").Rows.Count > 0 Then
dt = ds.Tables("Row").Copy()
For Each myrow As DataRow In dt.Rows
' myrow.Item(0) contains url of the document
If myrow.Item(0) IsNot Nothing AndAlso myrow.Item(0) <> "" Then
DownLoadAttachmentold(myrow.Item("ows_EncodedAbsUrl"), RemoveLookupID(myrow.Item("ows_FileLeafRef")))
End If
Next
End If
Public Shared Sub DownLoadAttachment(ByVal strURL As String, ByVal strFileName As String)
Dim myWebClient As New WebClient()
Dim DestinationFolder As String = "C:\\DownLoads\\"
Form2.RTBStatus.AppendText("Downloading File " + strFileName + " from " + strURL + " .......")
' The DownloadFile() method downloads the Web resource and saves it into the current file-system folder.
myWebClient.DownloadFile(strURL, DestinationFolder + strFileName)
'Form2.RTBStatus.AppendText("Successfully Downloaded file ""{0}"" from ""{1}""", "C:\\DownLoads\\" + strFileName, strURL)
Form2.RTBStatus.AppendText((ControlChars.Cr + "Downloaded file saved in the following file system folder:" + ControlChars.Cr + ControlChars.Tab + DestinationFolder))
End Sub
DownloadAttachment also needs to make (forms-based) authenticated HTTP requests.
An example in C# below:
request = (HttpWebRequest)WebRequest.Create(strURL);
request.Credentials = System.Net.CredentialCache.DefaultCredentials;//adapt for your FBA
request.AllowWriteStreamBuffering = false;
response = (HttpWebResponse)request.GetResponse();
Stream s = response.GetResponseStream();
FileStream fs = new FileStream(#"C:\DownLoads\"+strFileName, FileMode.Create);
Hi
I am using an ASP.NET application and producing a report in excel page with .csv extension. However I would like to produce it with .xlsx etension.
The code I am currently using is as follows:
Protected Sub btnSubmit_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnSubmit.Click
Dim sql As String
Dim strLine As String = ""
Dim attachment As String = "attachment; filename=PTW.csv"
m_sBranch = ddlBranches.SelectedValue
m_sRegion = ddlAreas.SelectedValue
Dim cnn As SqlConnection = New SqlConnection("Server=XYZ;Database=abc;Trusted_Connection=yes;")
HttpContext.Current.Response.AddHeader("content-disposition", attachment)
HttpContext.Current.Response.ContentType = "text/csv"
cnn.Open()
sql = GetReportSql(m_sBranch, m_sRegion)
Dim cmd As SqlCommand = New SqlCommand(sql, cnn)
Dim dr As SqlDataReader
dr = cmd.ExecuteReader()
HttpContext.Current.Response.Write("PTW JOBS - EXPORTED ON " + DateTime.Now)
For i = 0 To dr.FieldCount - 1
strLine = strLine & dr.GetName(i).ToString & ","
Next
HttpContext.Current.Response.Write(strLine)
Dim sb As StringBuilder = New StringBuilder()
Dim temp As String = ""
While dr.Read()
For i = 0 To dr.FieldCount - 1
temp = temp & dr.GetValue(i)
temp = temp.Replace(",", " ")
sb.Append(temp & ",")
temp = ""
Next
sb.AppendLine()
strLine = ""
End While
HttpContext.Current.Response.Write(sb.ToString())
End Sub
Any help will be highly appreciated. Thanks.
Look into the OpenXML SDK:
I understand that my example doesn't convert .csv files, but it will steer you in the right direction.
http://msdn.microsoft.com/en-us/library/bb448854(office.14).aspx
I've used it in asp.net to create xlsx documents on the fly, streamed directly to the web client:
public static System.IO.MemoryStream ConvertToExcel(DataSet ds)
{
System.IO.MemoryStream stream = new System.IO.MemoryStream();
using (SpreadsheetDocument package = SpreadsheetDocument.Create(stream, SpreadsheetDocumentType.Workbook, true))
{
package.AddWorkbookPart();
package.WorkbookPart.Workbook = new Workbook();
package.WorkbookPart.AddNewPart<WorksheetPart>();
if (ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
{
DataTable tbl = ds.Tables[0];
SheetData xlSheetData = new SheetData();
foreach (DataRow row in tbl.Rows)
{
Row xlRow = new Row();
foreach (DataColumn col in tbl.Columns)
{
object cellData = row[col];
Cell xlCell = null;
if (cellData != null)
{
xlCell = new Cell(new InlineString(new DocumentFormat.OpenXml.Spreadsheet.Text(cellData.ToString()))) { DataType = CellValues.InlineString };
}
else
{
xlCell = new Cell(new InlineString(new DocumentFormat.OpenXml.Spreadsheet.Text(String.Empty))) { DataType = CellValues.InlineString };
}
xlRow.Append(xlCell);
}
xlSheetData.Append(xlRow);
}
package.WorkbookPart.WorksheetParts.First().Worksheet = new Worksheet(xlSheetData);
package.WorkbookPart.WorksheetParts.First().Worksheet.Save();
// create the worksheet to workbook relation
package.WorkbookPart.Workbook.AppendChild(new Sheets());
package.WorkbookPart.Workbook.GetFirstChild<Sheets>().AppendChild(new Sheet()
{
Id = package.WorkbookPart.GetIdOfPart(package.WorkbookPart.WorksheetParts.First()),
SheetId = 1,
Name = "Sheet1"
});
package.WorkbookPart.Workbook.Save();
}
}
return stream;
}
Shariful, from what I've read (not tried yet), I believe the best method is to set your HTTP Response headers as outlined here.
In short, the key seems to be setting the content-disposition header to "attachment".
e.g.:
Content-Disposition: attachment; filename=<file name.ext>
Sorry that I haven't tested this, but in my searching for something closely related, almost every place I went suggests to use this method in order to force download dialog.