download datatable as a csv file - asp.net

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")

Related

Server cannot append header after HTTP headers have been sent. vb.net

I'm working on something where I should export an information to a csv file, but when I try to download it in the line Response.AddHeader(" content-disposition "attachment; filename = GridViewExport.csv")
I get the error:
Server can not append header after HTTP headers have been sent.
My gridview is inside og a update panel
Public Sub archivoGenerado()
For Each RW As GridViewRow In Dgdatoo.Rows
If CType(RW.Cells(10).FindControl("CheckBox2"), CheckBox).Checked = True Then
'If CType(RW.Cells(10).FindControl("Radio"), RadioButton).Checked = True Then
Dim estatus As [String] = CType(RW.Cells(8).FindControl("LabEs"), Label).Text
Dim Centro As [String] = DirectCast(RW.Cells(1).FindControl("LabeCe"), Label).Text
Dim almacen As [String] = DirectCast(RW.Cells(3).FindControl("LabeAl"), Label).Text
Dim Dupla As [String] = DirectCast(RW.Cells(6).FindControl("LabeDu"), Label).Text
Dim constr As New Data.SqlClient.SqlConnection
constr.ConnectionString = C.GetAppConfiguracion("Inventario", "ConnInventario")
Using cmd As New SqlCommand("Select Vw_RptInventarioSAP.IdMaterial as 'Barcode / Item-ID',Vw_RptInventarioSAP.MaterialNombre as'Description',S_AsignacionDuplas.Cantidad as 'Quantity',Vw_RptInventarioSAP.IdLote as 'Lote',S_AsignacionDuplas.IdCentro as 'Centro',S_AsignacionDuplas.IdAlamacen as 'Almacen',S_AsignacionDuplas.IdDupla as 'Dupla' from Vw_RptInventarioSAP inner join S_AsignacionDuplas on Vw_RptInventarioSAP.IdMaterial = S_AsignacionDuplas.IdMaterial where S_AsignacionDuplas.IdDupla = '" & Dupla & "' and IdCentro ='" & Centro & "' and IdAlmacen= '" & almacen & "'")
Using sda As New SqlDataAdapter()
cmd.Connection = constr
sda.SelectCommand = cmd
Dim da As New SqlDataAdapter(cmd)
Using dt As New DataTable()
sda.Fill(dt)
'Build the CSV file data as a Comma separated string.
Dim csv As New StringBuilder()
For i As Integer = 0 To dt.Columns.Count - 1
csv.Append(dt.Columns(i).ColumnName + ",")
Next
csv.Append(Environment.NewLine)
For j As Integer = 0 To dt.Rows.Count - 1
For k As Integer = 0 To dt.Columns.Count - 1
csv.Append(dt.Rows(j)(k).ToString() + ",")
Next
csv.Append(Environment.NewLine)
Next
For Each RW2 As GridViewRow In Dgdatoo.Rows
Response.Clear()
Response.ClearContent()
Response.ContentType = "text/csv"
Response.AddHeader("content-disposition","attachment;filename=GridViewExport.csv")
Response.Write(csv.ToString())
Response.Flush()
Next
'Next
End Using
End Using
End Using
Else
With lbError0
.Visible = True
.Text = "Selecionar inventario a descargar"
End With
End If
Next
End Sub

ssrs to byte and byte to pdf in memory

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

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

Any possible chance for a memory leak?

i get this error System.OutOfMemoryException: Exception of type 'System.OutOfMemoryException was thrown.` Why?? Kindly help me. I get this error (only when i host the website online, not in local machine).
Dim db As SqlDatabase = Connection.connection
Protected Sub btnSubmit_Click(sender As Object, e As System.EventArgs) Handles btnSubmit.Click
'Dim lblNodeID As Label = CType(Master.FindControl("lblParentId"), Label)
Using conn As DbConnection = db.CreateConnection()
Dim cmdInsertGroup As SqlCommand = db.GetSqlStringCommand("Insert Into CategoryGroups Values ('" & BLL.getNewGroupIDfromCategoryGroups & "','" & lblParentId.Text.Trim & "','" & txtGroupName.Text.Trim & "')")
Try
If fuGroupAttributes.HasFile Then
fuGroupAttributes.SaveAs(IO.Path.Combine(Server.MapPath("~/Admin/SpecificationExcels"), lblParentId.Text.Trim & IO.Path.GetExtension(fuGroupAttributes.FileName)))
Dim path As String = Server.MapPath("~/Admin/SpecificationExcels/" & lblParentId.Text.Trim & IO.Path.GetExtension(fuGroupAttributes.FileName))
Dim strmail As String = String.Empty
Dim connectionString As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & path & ";Extended Properties=Excel 12.0;"
Dim objConn As New OleDbConnection(connectionString)
objConn.Open()
Dim strConString As String = "SELECT * FROM [Sheet1$]"
'where date = CDate('" + DateTime.Today.ToShortDateString() + "')";
Dim objCmdSelect As New OleDbCommand(strConString, objConn)
' Create new OleDbDataAdapter that is used to build a DataSet
' based on the preceding SQL SELECT statement.
Dim objAdapter1 As New OleDbDataAdapter()
' Pass the Select command to the adapter.
objAdapter1.SelectCommand = objCmdSelect
' Create new DataSet to hold information from the worksheet.
Dim ds As New DataSet()
' Fill the DataSet with the information from the worksheet.
objAdapter1.Fill(ds, "ExcelData")
'My Exp
Dim _newAttributeID As Integer = BLL.getNewAttributeIDfromGroupAttributes
Dim _newGroupID As Integer
conn.Open()
Dim trans As DbTransaction = conn.BeginTransaction()
If cbInsertInExistingGroup.Checked Then
If gvExistingGroups.SelectedValue IsNot Nothing Then
_newGroupID = gvExistingGroups.SelectedRow.Cells(1).Text
Else
pnlMessage.Visible = True
pnlMessage.BackColor = Drawing.Color.Red
lblMessage.ForeColor = Drawing.Color.White
lblMessage.Font.Bold = True
lblMessage.Text = "Select a Group"
Exit Sub
End If
Else
_newGroupID = BLL.getNewGroupIDfromCategoryGroups
db.ExecuteNonQuery(cmdInsertGroup, trans)
End If
For i = 0 To ds.Tables(0).Rows.Count - 1
ds.Tables(0).Rows(i).Item(0) = _newAttributeID
ds.Tables(0).Rows(i).Item(1) = _newGroupID
_newAttributeID = _newAttributeID + 1
Next
' Clean up objects.
objConn.Close()
'Dim db As SqlDatabase = Connection.connection
Dim sqlBulk As New SqlBulkCopy(conn, SqlBulkCopyOptions.Default, trans)
sqlBulk.DestinationTableName = "GroupAttributes"
sqlBulk.WriteToServer(ds.Tables(0))
trans.Commit() ' commit the transaction
pnlMessage.Visible = True
pnlMessage.BackColor = Drawing.Color.Green
lblMessage.ForeColor = Drawing.Color.White
lblMessage.Font.Bold = True
lblMessage.Text = "Successfully Uploaded"
'Response.Redirect("~/Admin/AddSpecifications.aspx?id=" & Request.QueryString(0))
Else
pnlMessage.Visible = True
pnlMessage.BackColor = Drawing.Color.Red
lblMessage.ForeColor = Drawing.Color.White
lblMessage.Font.Bold = True
lblMessage.Text = "Select an Excel File"
'Response.Write("")
End If
Catch ex As Exception
trans.Rollback() ' rollback the transaction
pnlMessage.BackColor = Drawing.Color.Red
lblMessage.ForeColor = Drawing.Color.White
lblMessage.Font.Bold = True
lblMessage.Text = "Some Error Occured"
End Try
End Using
End Sub
Your code is a bit complicated to follow, but in this block you Exit Sub without closing the connection objConn
If cbInsertInExistingGroup.Checked Then
If gvExistingGroups.SelectedValue IsNot Nothing Then
_newGroupID = gvExistingGroups.SelectedRow.Cells(1).Text
Else
pnlMessage.Visible = True
pnlMessage.BackColor = Drawing.Color.Red
lblMessage.ForeColor = Drawing.Color.White
lblMessage.Font.Bold = True
lblMessage.Text = "Select a Group"
Exit Sub
End If
You should really try to refactor this huge block of code in more small units. In this way you could use the Using statement to dispose correctly of the Disposable objects like OleDbConnection, OleDbAdapter, OleDbCommand....

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