ssrs to byte and byte to pdf in memory - asp.net

I am trying to copy ssrs report to pdf in memory but i am getting error message when i open pdf 'file not in right format' . I am using asp.net and iTextSharp.
I want to copy ssrs to new pdf (rptpdf) file in memory and then open existing pdf and copy images to second page of that (rptpdf) pdf.
For testing purpose i am trying to see if i can copy ssrs to pdf.
Dim doc As New iTextSharp.text.Document()
Dim content As Byte()
Try
Using myMemoryStream As New MemoryStream()
Dim writer As iTextSharp.text.pdf.PdfWriter = iTextSharp.text.pdf.PdfWriter.GetInstance(doc, myMemoryStream)
doc.Open()
Dim cb As iTextSharp.text.pdf.PdfContentByte = writer.DirectContent
Dim page As iTextSharp.text.pdf.PdfImportedPage
'--- bytes = rptViewer.ServerReport.Render("PDF", "", "", "", "", Nothing, Nothing)
Dim b() As Byte = ReportRender.GetReport()
Dim reader2 As New iTextSharp.text.pdf.PdfReader(b)
Dim pages As Integer = reader2.NumberOfPages
For i As Integer = 1 To pages
doc.SetPageSize(iTextSharp.text.PageSize.LETTER)
doc.NewPage()
page = writer.GetImportedPage(reader2, i)
cb.AddTemplate(page, 0, 0)
Next
doc.Close()
reader2.Close()
writer.Close()
content = myMemoryStream.ToArray()
myMemoryStream.Close()
End Using
Response.ContentType = "application/pdf"
Response.AddHeader("content-disposition", "attachment;filename=" & "hello" & ".pdf")
Response.Cache.SetCacheability(HttpCacheability.NoCache)
Response.Write(content)
UPDATED
I have managed to copy reportviewer report byte to memory stream but at add pdf file (line "writer.AddPage(page)") i get error 'object not reference '
Using myMemoryStream As New MemoryStream()
Dim rptpdfwriter As iTextSharp.text.pdf.PdfWriter = iTextSharp.text.pdf.PdfWriter.GetInstance(doc, myMemoryStream)
If rptpdfwriter Is Nothing Then
Return
End If
doc.Open()
Dim cb As iTextSharp.text.pdf.PdfContentByte = rptpdfwriter.DirectContent
Dim page2 As iTextSharp.text.pdf.PdfImportedPage
'--- bytes = rptViewer.ServerReport.Render("PDF", "", "", "", "", Nothing, Nothing)
Dim b() As Byte = ReportRender.GetReport()
Dim reader2 As New iTextSharp.text.pdf.PdfReader(b)
Dim pages2 As Integer = reader2.NumberOfPages
For i As Integer = 1 To pages2
doc.SetPageSize(iTextSharp.text.PageSize.A4.Rotate)
doc.NewPage()
page2 = rptpdfwriter.GetImportedPage(reader2, i)
cb.AddTemplate(page2, 0, 0)
Next
reader2.Close()
For Each item As Expenses In expenses
Select Case item.Ext.ToLower
Case ".pdf"
Dim writer As New iTextSharp.text.pdf.PdfCopy(doc, myMemoryStream)
Dim reader As New iTextSharp.text.pdf.PdfReader(Server.MapPath("/docs/expenses/" + item.ExpenseID.ToString + item.Ext))
reader.ConsolidateNamedDestinations()
For i As Integer = 1 To reader.NumberOfPages
Dim page As iTextSharp.text.pdf.PdfImportedPage = writer.GetImportedPage(reader, i)
writer.AddPage(page)
Next
Dim form As iTextSharp.text.pdf.PRAcroForm = reader.AcroForm
If form IsNot Nothing Then
writer.CopyAcroForm(reader)
End If
reader.Close()
Case ".jpg"
Dim pdfWriter As iTextSharp.text.pdf.PdfWriter = iTextSharp.text.pdf.PdfWriter.GetInstance(doc, myMemoryStream)
Dim jpg As iTextSharp.text.Image = iTextSharp.text.Image.GetInstance(Server.MapPath("/docs/expenses/" + item.ExpenseID.ToString + item.Ext))
If Not doc.IsOpen Then doc.Open()
doc.Add(jpg)
Case Else
Exit Sub
End Select
Next
doc.Close()
Content = myMemoryStream.ToArray()
myMemoryStream.Flush()
myMemoryStream.Dispose()
Response.ContentType = "application/pdf"
Response.AppendHeader("Content-Disposition", "attachment; filename=LeftCorneraaa.pdf")
Response.BinaryWrite(Content)
End Using

Related

How to change gridview headings before exporting to pdf (Asp.Net VB)

I'm hoping you can help. I created a function that takes a dataset, binds it to a temp gridview and then exports it to pdf.
I need to somehow change the headings on the gridview before exporting to pdf so they are more user friendly. I added a RowDataBound event and then checked if the rowtype is a DataControlRowType.Header and tried modifying it that way but i'm still seeing the un altered version from the dataset. Here is my code so far:
Dim context As HttpContext = HttpContext.Current
Dim response As HttpResponse = HttpContext.Current.Response
Dim tmpGridView As New GridView()
tmpGridView.BorderWidth = 0
tmpGridView.ControlStyle.Font.Size = 8
tmpGridView.AllowPaging = False
tmpGridView.DataSource = ds
tmpGridView.DataBind()
AddHandler tmpGridView.RowDataBound, AddressOf tmpGridView_RowDataBound
response.ContentType = "application/pdf"
response.AddHeader("Content-Disposition", "attachment;filename=""" & filename & """")
response.Cache.SetCacheability(HttpCacheability.NoCache)
Dim sw As New StringWriter()
Dim hw As New HtmlTextWriter(sw)
tmpGridView.RenderControl(hw)
Dim sr As New StringReader(sw.ToString())
Dim pdfDoc As New Document()
pdfDoc.SetMargins(20.0F, 20.0F, 20.0F, 20.0F)
If Rotation = "Vertical" Then
pdfDoc.SetPageSize(PageSize.A4)
ElseIf Rotation = "Horizontal" Then
pdfDoc.SetPageSize(PageSize.A4.Rotate())
End If
Dim Image As String = context.Server.MapPath("~/Images/head_logo.gif")
Dim headerImage As iTextSharp.text.Image = iTextSharp.text.Image.GetInstance(Image)
headerImage.ScalePercent(100.0F)
headerImage.Alignment = Element.ALIGN_LEFT
headerImage.SpacingAfter = 50.0F
Dim HeadingFont As iTextSharp.text.Font = FontFactory.GetFont(FontFactory.HELVETICA_BOLD, 12)
Dim ParagraphFont As iTextSharp.text.Font = FontFactory.GetFont(FontFactory.HELVETICA, 8)
Dim htmlparser As New HTMLWorker(pdfDoc)
Dim writer As PdfWriter = PdfWriter.GetInstance(pdfDoc, response.OutputStream)
pdfDoc.Open()
Dim cb As PdfContentByte = writer.DirectContent
pdfDoc.Add(headerImage)
Dim ct As New ColumnText(cb)
Dim heading As New Phrase(ReportName, HeadingFont)
ct.SetSimpleColumn(heading, 480, 780, 50, 50, 10, Element.ALIGN_RIGHT)
ct.Go()
pdfDoc.Add(New Paragraph("Generated on " & Date.Now.ToString("dd MMMM yyyy"), ParagraphFont))
pdfDoc.Add(New Paragraph(vbCrLf))
htmlparser.Parse(sr)
pdfDoc.Close()
response.Write(pdfDoc)
response.End()
And here is the code in my tmpGridView_RowDataBound event
If e.Row.RowType = DataControlRowType.Header Then
Dim Heading1Value As String = e.Row.Cells(0).Text
Select Case Heading1Value
Case "SaleID"
e.Row.Cells(0).Text = "ID"
End Select
End If
Any help would be appreciated. Thanks
Turns out I was executing the code in the wrong order.
AddHandler tmpGridView.RowDataBound, AddressOf tmpGridView_RowDataBound
The above line of code needed to be added before
tmpGridView.DataBind()
Otherwise the event wasn't being fired. Sorted now.

itextsharp pdfsmartcopy only returning last page

I have an issue where only the last page of my pdf is stored.
The pdf should be multiple pages long, and this works fine if I just send the pdf to the browser using Response and the mms memory stream, however I need to add it as a pdf to an email and therefore are writing mms to bytes to create a new memorystream when I create my email attachment. This is to get around the closed stream error.
This is my code
Public Shared Function SendPrePackLabels(ByVal bf_id As String, mail As String) As Boolean
Dim pars(0) As SqlParameter
pars(0) = New SqlParameter("#bf_id", SqlDbType.VarChar) With {.Value = bf_id}
Dim p As String
Dim reader As PdfReader
Dim mms As New MemoryStream
Dim rt() As Byte
Dim i As Integer = 0
Using dc As Document = New Document
Using sc As PdfSmartCopy = New PdfSmartCopy(dc, System.Web.HttpContext.Current.Response.OutputStream)
dc.Open()
With SqlHelper.ExecuteDataset(Stiletto.cnStrRMIS, CommandType.StoredProcedure, "BPM_spPrepack_Labels", pars).Tables(0)
For Each dr As DataRow In .Rows
Dim pdfr As New PdfReader("http://192.168.0.221/template.pdf")
Using ms As New MemoryStream
Using pdfs As New PdfStamper(pdfr, ms)
Dim fields As AcroFields = pdfs.AcroFields
fields.GenerateAppearances = True
fields.SetField("pono", dr.Item("po_no").ToString)
fields.SetField("ref", dr.Item("alt_code").ToString)
fields.SetField("colour", dr.Item("colour").ToString)
fields.SetField("code", dr.Item("sizerun_hdr_id").ToString)
For k As Integer = 1 To dr.Table.Columns.Count - 6
Dim j As Integer = k + 5
fields.SetField("s" & k, dr.Table.Columns(j).ColumnName.ToString)
If dr.Item(dr.Table.Columns(j).ColumnName.ToString).ToString = "" Then
p = "0"
Else
p = dr.Item(dr.Table.Columns(j).ColumnName.ToString).ToString
End If
fields.SetField("p" & k, p)
Next
fields.SetField("pack", dr.Item("sizerun_hdr_id").ToString)
Dim bcfont As BaseFont = BaseFont.CreateFont("http://192.168.0.221/ean.ttf", BaseFont.CP1252, BaseFont.EMBEDDED)
fields.SetFieldProperty("barcode", "textfont", bcfont, Nothing)
fields.SetFieldProperty("barcode", "textsize", 60.0F, Nothing)
Dim mBarcode As String = "219" & dr.Item("sizerun_hdr_id").ToString
Dim cLength As Integer = mBarcode.Length
Dim zerostoadd As Integer = 12 - cLength
Dim digit12barcode As String = mBarcode.PadRight(12, CChar("0"))
Dim FinalBarcode As String = returnCheckDigitedBarcode(digit12barcode)
fields.SetField("barcode", FinalBarcode)
Dim par(1) As SqlParameter
par(0) = New SqlParameter("#sizerun_hdr_id", SqlDbType.VarChar) With {.Value = dr.Item("sizerun_hdr_id").ToString}
par(1) = New SqlParameter("#ean13", SqlDbType.VarChar) With {.Value = FinalBarcode}
SqlHelper.ExecuteScalar(Stiletto.cnStrRMIS, CommandType.StoredProcedure, "BPM_spSizeRunEAN13", par)
pdfs.FormFlattening = True
ms.Flush()
End Using
reader = New PdfReader(ms.ToArray)
sc.AddPage(sc.GetImportedPage(reader, 1))
mms = ms
End Using
Next
End With
End Using
End Using
Dim bt() As Byte = mms.ToArray
Try
If mail.Length > 0 Then
Dim eMsg As New MailMessage()
eMsg.From = New MailAddress("myemail#mydomain.co.uk")
eMsg.To.Add(New MailAddress(mail))
Dim title As String = "<h3>Here are the Prepack Labels.</h3>"
eMsg.Subject = "Prepack Labels"
eMsg.Body = "<html>" & title & "</html>"
eMsg.IsBodyHtml = True
Dim att As Attachment = New Attachment(New MemoryStream(bt), "Prepack Labels.pdf", "application/pdf")
eMsg.Attachments.Add(att)
Dim SMTP1 As New SmtpClient
SMTP1.Host = "EX"
SMTP1.Send(eMsg)
att.Dispose()
End If
Return True
Catch ex As Exception
Return False
End Try
End Function
I'm not sure of your exact problem but I'm pretty sure your life would be easier if you broke you giant function into smaller more specific functions that do only one thing. Also, I really recommend never writing to the raw ASP.Net stream until after you've created a PDF. Instead, always write to a MemoryStream, grab the bytes and do something with them.
The code below break it into four functions. CreatePdf() loops through the database and calls CreateSinglePdf() for each row in the table, merging them with your PdfSmartCopy. SendEmail() is blissfully unaware of iTextSharp completely and just receives a raw array of bytes that is assumed to be a PDF. This is all kicked off by SendPrePackLabels() which is where you'd probably want to also Response.BinaryWrite() your bytes.
Public Shared Function SendPrePackLabels(ByVal bf_id As String, mail As String) As Boolean
Dim bt = CreatePdf(bf_id)
Return SendEmail(bt, mail)
End Function
Public Shared Function CreateSinglePdf(dr As DataRow) As Byte()
Using ms As New MemoryStream
Using pdfr As New PdfReader("http://192.168.0.221/template.pdf")
Using pdfs As New PdfStamper(pdfr, ms)
Dim fields As AcroFields = pdfs.AcroFields
fields.GenerateAppearances = True
fields.SetField("pono", dr.Item("po_no").ToString)
fields.SetField("ref", dr.Item("alt_code").ToString)
fields.SetField("colour", dr.Item("colour").ToString)
fields.SetField("code", dr.Item("sizerun_hdr_id").ToString)
Dim p As String
For k As Integer = 1 To dr.Table.Columns.Count - 6
Dim j As Integer = k + 5
fields.SetField("s" & k, dr.Table.Columns(j).ColumnName.ToString)
If dr.Item(dr.Table.Columns(j).ColumnName.ToString).ToString = "" Then
p = "0"
Else
p = dr.Item(dr.Table.Columns(j).ColumnName.ToString).ToString
End If
fields.SetField("p" & k, p)
Next
fields.SetField("pack", dr.Item("sizerun_hdr_id").ToString)
Dim bcfont As BaseFont = BaseFont.CreateFont("http://192.168.0.221/ean.ttf", BaseFont.CP1252, BaseFont.EMBEDDED)
fields.SetFieldProperty("barcode", "textfont", bcfont, Nothing)
fields.SetFieldProperty("barcode", "textsize", 60.0F, Nothing)
Dim mBarcode As String = "219" & dr.Item("sizerun_hdr_id").ToString
Dim cLength As Integer = mBarcode.Length
Dim zerostoadd As Integer = 12 - cLength
Dim digit12barcode As String = mBarcode.PadRight(12, CChar("0"))
Dim FinalBarcode As String = returnCheckDigitedBarcode(digit12barcode)
fields.SetField("barcode", FinalBarcode)
Dim par(1) As SqlParameter
par(0) = New SqlParameter("#sizerun_hdr_id", SqlDbType.VarChar) With {.Value = dr.Item("sizerun_hdr_id").ToString}
par(1) = New SqlParameter("#ean13", SqlDbType.VarChar) With {.Value = FinalBarcode}
SqlHelper.ExecuteScalar(Stiletto.cnStrRMIS, CommandType.StoredProcedure, "BPM_spSizeRunEAN13", par)
pdfs.FormFlattening = True
End Using
End Using
Return ms.ToArray()
End Using
End Function
Public Shared Function CreatePdf(ByVal bf_id As String) As Byte()
Dim pars(0) As SqlParameter
pars(0) = New SqlParameter("#bf_id", SqlDbType.VarChar) With {.Value = bf_id}
Using ms As New System.IO.MemoryStream
Using dc As Document = New Document
Using sc As PdfSmartCopy = New PdfSmartCopy(dc, ms)
dc.Open()
With SqlHelper.ExecuteDataset(Stiletto.cnStrRMIS, CommandType.StoredProcedure, "BPM_spPrepack_Labels", pars).Tables(0)
For Each dr As DataRow In .Rows
Dim pageBytes = CreateSinglePdf(dr)
Using reader = New PdfReader(pageBytes)
sc.AddPage(sc.GetImportedPage(reader, 1))
End Using
Next
End With
End Using
End Using
Return ms.ToArray()
End Using
End Function
Public Shared Function SendEmail(bt As Byte(), mail As String) As Boolean
Try
If mail.Length > 0 Then
Dim eMsg As New MailMessage()
eMsg.From = New MailAddress("myemail#mydomain.co.uk")
eMsg.To.Add(New MailAddress(mail))
Dim title As String = "<h3>Here are the Prepack Labels.</h3>"
eMsg.Subject = "Prepack Labels"
eMsg.Body = "<html>" & title & "</html>"
eMsg.IsBodyHtml = True
Dim att As Attachment = New Attachment(New MemoryStream(bt), "Prepack Labels.pdf", "application/pdf")
eMsg.Attachments.Add(att)
Dim SMTP1 As New SmtpClient
SMTP1.Host = "EX"
SMTP1.Send(eMsg)
att.Dispose()
End If
Return True
Catch ex As Exception
Return False
End Try
End Function

changing the way of coding so that MS Excel is not to be needed to installed on server in asp.net

I have started to deveop a website using asp.net.
I need to fetch some data from excel to display it to the client.
I am hosting my site on somee.com so that I can freely host it.
But on the server of somee.com Excel is not installed.
I have written some code for my website to display the data from from excel.
Dim xlApp As New Microsoft.Office.Interop.Excel.Application()
Dim xlWorkbook As Microsoft.Office.Interop.Excel.Workbook = xlApp.Workbooks.Open(FileUploadPath & sender.text)
Dim xlWorksheet As Microsoft.Office.Interop.Excel._Worksheet = xlWorkbook.Sheets(SheetName)
Dim xlRange As Microsoft.Office.Interop.Excel.Range = xlWorksheet.UsedRange
Dim rowCount As Integer = xlRange.Rows.Count
Dim colCount As Integer = xlRange.Columns.Count
Dim tbl As New DataTable()
For i As Integer = 1 To rowCount
tbl.Rows.Add()
Next
For i As Integer = 1 To colCount
tbl.Columns.Add()
Next
If rowCount > 1 Or colCount > 1 Then
For i As Integer = 1 To rowCount
For j As Integer = 1 To colCount
tbl.Rows(i - 1)(j - 1) = xlRange.Value2(i, j)
Next j
Next i
End If
gvReadFiles.AutoGenerateColumns = True
gvReadFiles.DataSource = tbl
gvReadFiles.DataBind()
xlApp.ActiveWorkbook.Close(False, Session(FileUploadPath & sender.text))
xlApp.Quit()
xlWorkbook = Nothing
xlApp = Nothing
Now I need to have some changes in code so it is not excel dependent.
Can you help me?
I solved it using google for more than 2 hours.
Here is the code
Dim objConn As OleDbConnection = Nothing
Dim dt As System.Data.DataTable = Nothing
Try
Dim connString As String = ""
If Extension = "xls" Or Extension = ".xls" Then
connString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & FileUploadPath & sender.text & ";Extended Properties=" + Convert.ToChar(34).ToString() + "Excel 8.0;HDR=No;IMEX=1" + Convert.ToChar(34).ToString() + ""
ElseIf Extension = "xlsx" Or Extension = ".xlsx" Then
connString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & FileUploadPath & sender.text & ";Extended Properties=" + Convert.ToChar(34).ToString() + "Excel 12.0;HDR=No;IMEX=1" + Convert.ToChar(34).ToString() + ""
End If
objConn = New OleDbConnection(connString)
objConn.Open()
dt = objConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, Nothing)
Dim firstSheetName As String = "Sheet1"
If Not dt Is Nothing Then
Dim excelSheets As [String]() = New [String](dt.Rows.Count - 1) {}
' Add the sheet name to the string array.
For Each row As DataRow In dt.Rows
firstSheetName = row("TABLE_NAME").ToString().Substring(0, row("TABLE_NAME").ToString.Length - 1)
Exit For
Next
End If
Return firstSheetName
Catch ex As Exception
Return "Sheet1"
Finally
If objConn IsNot Nothing Then
objConn.Close()
objConn.Dispose()
End If
If dt IsNot Nothing Then
dt.Dispose()
End If
End Try

download datatable as a csv file

Hi all I am trying to allow the user to download data from a database so they can manipulate it with out having access to the database. so far I have this it makes the file but I need it to download to the client pc. Any tips?
Protected Sub ExportDataTableToCSV(cmdText As String)
Try
Dim sqlcon_Local As New SqlClient.SqlConnection
sqlcon_Local.ConnectionString = ConfigurationManager.ConnectionStrings("Portal").ConnectionString
Dim objCmd As New SqlCommand(cmdText, sqlcon_Local)
Dim da As SqlDataAdapter = New SqlDataAdapter(objCmd)
Dim dt As DataTable = New DataTable
da.Fill(dt)
Dim filename As String = Server.MapPath("~/download.csv")
Dim sw As New StreamWriter(filename, False)
Dim iColCount As Integer = dt.Columns.Count
For i As Integer = 0 To iColCount - 1
sw.Write(dt.Columns(i))
If i < iColCount - 1 Then
sw.Write(",")
End If
Next
sw.Write(sw.NewLine)
For Each dr As DataRow In dt.Rows
For i As Integer = 0 To iColCount - 1
If Not Convert.IsDBNull(dr(i)) Then
sw.Write(dr(i).ToString())
End If
If i < iColCount - 1 Then
sw.Write(",")
End If
Next
sw.Write(sw.NewLine)
Next
sw.Close()
Response.Clear()
Response.ContentType = "application/csv"
Response.AddHeader("Content-Disposition", "attachment; filename=download.csv")
Response.WriteFile(filename)
Response.Flush()
Response.End()
Catch ex As Exception
End Try
End Sub
what am I doing wrong?
any input will be welcome.
Thanks for your time!
please change Response.ContentType as
Response.ContentType = "text/csv";
hope this will help you
Public Shared Function Export_CSV(ByVal cmdText As String) As String
Dim message As String = Nothing
Try
Dim sqlcon_Local As New SqlClient.SqlConnection
sqlcon_Local.ConnectionString = ConfigurationManager.ConnectionStrings("Portal").ConnectionString
Dim objCmd As New SqlCommand(cmdText, sqlcon_Local)
Dim da As SqlDataAdapter = New SqlDataAdapter(objCmd)
Dim dt As DataTable = New DataTable
da.Fill(dt)
Dim context As HttpContext = HttpContext.Current
context.Response.Clear()
For Each column As DataColumn In dt.Columns
context.Response.Write(column.ColumnName + ",")
Next
context.Response.Write(Environment.NewLine)
For Each row As DataRow In dt.Rows
For i As Integer = 0 To dt.Columns.Count - 1
context.Response.Write(row(i).ToString.Replace(",", String.Empty) + ",")
Next
context.Response.Write(Environment.NewLine)
Next
context.Response.ContentType = "txt/csv"
context.Response.AppendHeader("Content-Disposition", "attachment; filename=" + download + ".csv")
HttpContext.Current.ApplicationInstance.CompleteRequest()
message = "Export Successful"
Catch ex As Exception
message = ex.Message.ToString
End Try
Return message
End Function
ref : http://www.thewebbureau.com/tech_blog/post/Export-DataTable-To-CSV.aspx
If you have problem with IE browser
change
context.Response.AppendHeader("Content-Disposition", "attachment; filename=" + download + ".csv")
to
context.Response.AppendHeader("Content-Disposition", "attachment; inline=" + download + ".csv")

export from sql server to excel file using asp.net and vb.net?

is there a way to export the whole data in one table from sql server 2008 directly using asp.net and vb.net without using datagridview to EXCEL FILE?
Basically, you just need to loop over the columns and rows of your DataTable in order to output them to the response. This link shows you how.
In C#:
DataTable dt = GetData();
string attachment = "attachment; filename=Employee.xls";
Response.ClearContent();
Response.AddHeader("content-disposition", attachment);
Response.ContentType = "application/vnd.ms-excel";
string tab = "";
foreach (DataColumn dc in dt.Columns)
{
Response.Write(tab + dc.ColumnName);
tab = "\t";
}
Response.Write("\n");
int i;
foreach (DataRow dr in dt.Rows)
{
tab = "";
for (i = 0; i < dt.Columns.Count; i++)
{
Response.Write(tab + dr[i].ToString());
tab = "\t";
}
Response.Write("\n");
}
Response.End();
In VB.NET
Dim dt As DataTable = GetData()
Dim attachment As String = "attachment; filename=Employee.xls"
Response.ClearContent()
Response.AddHeader("content-disposition", attachment)
Response.ContentType = "application/vnd.ms-excel"
Dim tab As String = ""
For Each dc As DataColumn In dt.Columns
Response.Write(tab + dc.ColumnName)
tab = vbTab
Next
Response.Write(vbLf)
Dim i As Integer
For Each dr As DataRow In dt.Rows
tab = ""
For i = 0 To dt.Columns.Count - 1
Response.Write(tab & dr(i).ToString())
tab = vbTab
Next
Response.Write(vbLf)
Next
Response.End()
Set the contenttype of your page to "ContentType="application/vnd.ms-excel""
and the response.write all you column header to "th" and all data to "tr"'s with "td"
var exceltable = new StringBuilder();
exceltable.Append("<HTML><BODY><TABLE Border=0>");
exceltable.AppendFormat("<TR>");
exceltable.AppendFormat(string.Concat("<TD>Merchantname</TD>"));
exceltable.AppendFormat(string.Concat("<TD>Pendingstatus</TD>"));
exceltable.AppendFormat(string.Concat("<TD>Date</TD>"));
exceltable.AppendFormat(string.Concat("<TD>Ordervalue</TD>"));
exceltable.AppendFormat(string.Concat("<TD>Customer commision</TD>"));
exceltable.AppendFormat(string.Concat("<TD>Affiliate commision</TD>"));
exceltable.AppendFormat(string.Concat("<TD>Customerid</TD>"));
exceltable.AppendFormat(string.Concat("<TD>Paid</TD>"));
exceltable.AppendFormat(string.Concat("<TD>Paid date</TD>"));
exceltable.AppendFormat("</TR>");
foreach (DataRow row in dt.Rows)
{
exceltable.AppendFormat("<TR>");
exceltable.AppendFormat(string.Concat("<TD>", row["NAME"].ToString(), "</TD>"));
exceltable.AppendFormat(string.Concat("<TD>", row["pendingstatus"].ToString(), "</TD>"));
exceltable.AppendFormat(string.Concat("<TD>", row["datetimeclickout"].ToString(), "</TD>"));
exceltable.AppendFormat(string.Concat("<TD>", row["ordervalue"].ToString(), "</TD>"));
exceltable.AppendFormat(string.Concat("<TD>", row["customercommision"].ToString(), "</TD>"));
exceltable.AppendFormat(string.Concat("<TD>", row["affiliatecommision"].ToString(), "</TD>"));
exceltable.AppendFormat(string.Concat("<TD>", row["user_id"].ToString(), "</TD>"));
exceltable.AppendFormat(string.Concat("<TD>", row["paid"].ToString(), "</TD>"));
exceltable.AppendFormat(string.Concat("<TD>", row["paiddate"].ToString(), "</TD>"));
exceltable.AppendFormat("</TR>");
}
exceltable.Append("</TABLE></BODY></HTML>");
Response.Write(exceltable.ToString());
On page load you will be asked to save the file. Save it on your desktop and open it with Excel
what is the code to make it display table records in pdf with out a data grid.`enter code he this is the code im using.
Private Sub Command1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Command1.Click
Dim startTime As Date
Command1.Enabled = False
startTime = Now()
lblEnd.Text = ""
Dim clPDF As New clsPDFCreator
Dim strFile As String
Dim i As Integer
' output NAME
strFile = App_Path & "\Demo.pdf"
With clPDF
.Title = "Pay Day Report" ' TITLE
.ScaleMode = clsPDFCreator.pdfScaleMode.pdfCentimeter
.PaperSize = clsPDFCreator.pdfPaperSize.pdfA4 ' PAGE FORMAT
.Margin = 0 ' Margin
.Orientation = clsPDFCreator.pdfPageOrientation.pdfPortrait ' ORIENTATION
.EncodeASCII85 = chkASCII85.Checked
.InitPDFFile(strFile)
' DEFINING FONT
.LoadFont("Fnt1", "Times New Roman")
.LoadFont("Fnt2", "Arial", clsPDFCreator.pdfFontStyle.pdfItalic)
.LoadFont("Fnt3", "Courier New")
.LoadFontStandard("Fnt4", "Courier New", clsPDFCreator.pdfFontStyle.pdfBoldItalic)
.LoadImgFromBMPFile("Img1", App_Path & "\img\20x20x24.bmp")
.LoadImgFromBMPFile("Img2", App_Path & "\img\200x200x24.bmp")
For i = 0 To 5
' open a page
.BeginPage()
.DrawText(19, 1.5, "page " & Trim(CStr(.Pages)), "Fnt1", 12, clsPDFCreator.pdfTextAlign.pdfAlignRight)
.DrawObject("Footers")
.DrawText(10.5, 27, "Unifrieght Sage", "Fnt1", 18, clsPDFCreator.pdfTextAlign.pdfCenter)
.SetTextHorizontalScaling(70)
.DrawText(20, 25, "Regnumber", "Fnt2", 14, clsPDFCreator.pdfTextAlign.pdfAlignRight)
.DrawText(1, 25, "Name", "Fnt2", 14, clsPDFCreator.pdfTextAlign.pdfAlignLeft)
.DrawText(10.5, 25, "Surname", "Fnt2", 14, clsPDFCreator.pdfTextAlign.pdfCenter)
.SetTextHorizontalScaling(100)
Dim Name1 As String
Dim Surname As String
Dim Regnumber As String
Dim dt As DataTable
Dim tab As String = ""
Dim a As Integer
Dim cmd As OdbcCommand = New OdbcCommand("Select *from tblMain ", cn)
cmd.CommandType = CommandType.Text
Dim DR As OdbcDataReader = cmd.ExecuteReader
For Each dc As DataColumn In dt.Columns
'.DrawText(tab + dc.ColumnName)
tab = vbTab
Next
While DR.Read
Name1 = DR("name")
Surname = DR("surname")
Regnumber = ("regnumber")
Dim i As Integer
For Each drk As DataRow In dt.Rows
tab = ""
For i = 0 To dt.Columns.Count - 1
.SetTextHorizontalScaling(70)
.DrawText(20, 23 - a, Regnumber, "Fnt2", 14, clsPDFCreator.pdfTextAlign.pdfAlignRight)
.DrawText(1, 23 - a, Name1, "Fnt2", 14, clsPDFCreator.pdfTextAlign.pdfAlignLeft)
.DrawText(10.5, 23 - a, Surname, "Fnt2", 14, clsPDFCreator.pdfTextAlign.pdfCenter)
.SetTextHorizontalScaling(100)
tab = vbTab
Next
Next
.SetCharSpacing(3)
End While
.EndPage()
' this is for the footers
.StartObject("Footers", clsPDFCreator.pdfObjectType.pdfAllPages)
.DrawText(10, 1.5, "Designed by Renegate", "Fnt3", 8, clsPDFCreator.pdfTextAlign.pdfCenter)
.DrawText(20, 1.5, " of " & Trim(CStr(.Pages)), "Fnt1", 12, clsPDFCreator.pdfTextAlign.pdfAlignRight)
.EndObject()
Next
' closing the document
.ClosePDFFile()
End With
Dim Elapsed As TimeSpan = Now().Subtract(startTime)
lblEnd.Text = Elapsed.ToString()
Command1.Enabled = True
Call Shell("rundll32.exe url.dll,FileProtocolHandler " & (strFile), vbMaximizedFocus)
End Sub
you can try Office Interop which can create and manipulate Office formats.
beware, however- it has TERRIBLE performance issues, and MS officialy recommend NOT to use it on production servers, but rather- on client machines. (although it may have changed for office 2007 and upwards).
If you need alternatives- there are plenty of plugins for creating PDF documents, for example.
also- see this question.
The way I've done it in the past is to create a CSV file from a DataTable. Here's one nice example using extension methods to the DataTable class:
http://blog.runxc.com/post/2009/06/24/Exporting-a-DataTable-to-Excel-(DataTable-to-CSV).aspx
After you add that extension method to your project, you could output the CSV to the response stream like this:
Response.ContentType = "application/vnd.ms-excel";
Response.ContentEncoding = new System.Text.UTF8Encoding();
Response.AddHeader("content-disposition", "attachment; filename=report.xls");
Response.Write(myDataTable.toCSV());
Response.End();
for me this is was the right answer
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim ad As New results()
Dim dt As results.ResultsDataTable
dt = ad.Read()
Dim attachment As String = "attachment; filename=USurvey.xls"
Response.ClearContent()
Response.AddHeader("content-disposition", attachment)
Response.ContentType = "application/vnd.ms-excel"
Dim tab As String = ""
For Each dc As DataColumn In dt.Columns
Response.Write(tab + dc.ColumnName)
tab = vbTab
Next
Response.Write(vbLf)
Dim i As Integer
For Each dr As DataRow In dt.Rows
tab = ""
For i = 0 To dt.Columns.Count - 1
Response.Write(tab & dr(i).ToString())
tab = vbTab
Next
Response.Write(vbLf)
Next
Response.[End]()
'export to excel
End Sub
thanks a lot every one !!!

Resources