Server cannot append header after HTTP headers have been sent. vb.net - asp.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

Related

Query string not retrieving data values

Hope you guys could give me some help.
I have a asp.net web form which gets data from SQL database and displays it on webpage via product code number or product description.
Searching by description will display a list of similar products where each list will have a button with the product code when clicked will open another site with extra product information,
e.g.
13892
14589
17485
00010
08890
The problem is all the codes that start from 1 upwards will show more details, but when I click on product codes that start with 0 such as 00010, 08890 will show no data when in fact there should be data.
Any help would be appreciated.
code I have below,
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Val(Request.QueryString("Stock_code")) <> 0 Then
Dim dt As DataTable = New DataTable
Dim strQuery As String = "SELECT STKCODE as [Stock_Code], STKNAME as [Stock_Description], STK_BASEPRICE as [Retail_Price], STK_SORT_KEY2 as [Pack_Size], STK_NOTES as [Notes], STK_P_WEIGHT as [Net_Weight], STK_S_WEIGHT as [Gross_Weight] FROM dbo.STK_STOCK WHERE STKCODE = '" & Val(Request.QueryString("Stock_code")) & "'"
Dim strQUery2 As String = "SELECT LOC_CODE as [Location_Code], LOC_NAME as [Location], LOC_PHYSICAL as [Physical_Stock] FROM dbo.STK_LOCATION WHERE LOC_CODE IN ('WH01','WH03','WH04','WH08','WH11')" & _
"AND LOC_STOCK_CODE = '" & Val(Request.QueryString("Stock_code")) & "'"
Dim strQuery3 As String = "SELECT STKLANG_STOCKNAME as [Chinese_Description] FROM dbo.STK_STOCK_LANG WHERE STKLANG_STOCKCODE ='" & Val(Request.QueryString("stock_code")) & "'"
Dim strQuery4 = "SELECT STK_SELLPRICE1 as [Retail_Price], STK_SELLPRICE5 as [Retail_Rest_Split] FROM dbo.STK_STOCK_2 WHERE STKCODE2 = '" & Val(Request.QueryString("stock_code")) & "'"
Using cmd4 As SqlCommand = New SqlCommand(strQuery4)
Dim da3 As SqlDataAdapter = New SqlDataAdapter
Dim dt4 As New DataTable
cmd4.Connection = cnn : cnn.Open()
da3.SelectCommand = cmd4
da3.Fill(dt4)
For i = 0 To dt4.Rows.Count - 1
Label8.Text = dt4.Rows(i).Item("Retail_Rest_Split")
Next
End Using
cnn.Close()
Using cmd As SqlCommand = New SqlCommand(strQuery)
Dim sda As SqlDataAdapter = New SqlDataAdapter
cmd.Connection = cnn : cnn.Open()
sda.SelectCommand = cmd
sda.Fill(dt)
For i = 0 To dt.Rows.Count - 1
Label7.Text = dt.Rows(i).Item("Stock_Code")
Label1.Text = dt.Rows(i).Item("Notes")
Label3.Text = dt.Rows(i).Item("Retail_Price")
Label4.Text = dt.Rows(i).Item("Pack_Size")
Label5.Text = dt.Rows(i).Item("Stock_Description")
'Label8.Text = dt.Rows(i).Item("Pack_Size")
Label9.Text = dt.Rows(i).Item("Net_Weight")
Label10.Text = dt.Rows(i).Item("Gross_Weight")
GridView1.DataSource = dt
GridView1.DataBind()
Next
End Using
cnn.Close()
Dim dt3 As DataTable = New DataTable
Using cmd3 As SqlCommand = New SqlCommand(strQuery3)
Dim da2 As SqlDataAdapter = New SqlDataAdapter
cmd3.Connection = cnn : cnn.Open()
da2.SelectCommand = cmd3
da2.Fill(dt3)
End Using
For i = 0 To dt3.Rows.Count - 1
Label6.Text = dt3.Rows(i).Item("Chinese_Description")
Next
Dim cmd2 As New SqlCommand
Dim dt2 As New DataTable
Dim da As New SqlDataAdapter
With cmd2
.Connection = cnn
.CommandText = strQUery2
End With
da.SelectCommand = cmd2
da.Fill(dt2)
GridView1.DataSource = dt2
GridView1.DataBind()
End If
End Sub
You want to use a paramaterized query like this (I'm going to fold that query string to make it more readable without having to scroll horizontally):
Dim strQuery As String = "SELECT STKCODE as [Stock_Code], STKNAME as [Stock_Description],
STK_BASEPRICE as [Retail_Price], STK_SORT_KEY2 as
[Pack_Size], STK_NOTES as [Notes], STK_P_WEIGHT as
[Net_Weight], STK_S_WEIGHT as [Gross_Weight] FROM
dbo.STK_STOCK WHERE STKCODE = #StockCode"
Using cmd As New SqlCommand(strQuery)
cmd.Parameters.AddWithValue("#StockCode", Request.QueryString("Stock_code"))
' Do your other stuff here.
End Using
Note, that you don't want to just use string concatenation to insert your query parameter. That opens you up to SQL injection attacks.
Instead, you use a placeholder in your query like #StockCode. Then you call AddWithValue on the command to give it the value of that parameter.
You can also explicitly specify the parameter type if you need to:
' Add CustomerID parameter for WHERE clause.
command.Parameters.Add("#ID", SqlDbType.Int)
command.Parameters("#ID").Value = customerID
Assuming they are all 5 digit codes, this will make sure the stock code is numeric.
Replace
Val(Request.QueryString("Stock_code"))
with
String.Format("{0:00000}", Integer.Parse(Request.QueryString("Stock_code")))
Will raise an exception if Request.QueryString("Stock_code") is not parsed as integer, which prevents against malicious injection.
For example:
Dim stockCode = String.Format("{0:00000}", Integer.Parse(Request.QueryString("Stock_code")))
Dim strQuery As String = "SELECT STKCODE as [Stock_Code], STKNAME as [Stock_Description], STK_BASEPRICE as [Retail_Price], STK_SORT_KEY2 as [Pack_Size], STK_NOTES as [Notes], STK_P_WEIGHT as [Net_Weight], STK_S_WEIGHT as [Gross_Weight] FROM dbo.STK_STOCK WHERE STKCODE = '" & stockCode & "'"
Dim strQUery2 As String = "SELECT LOC_CODE as [Location_Code], LOC_NAME as [Location], LOC_PHYSICAL as [Physical_Stock] FROM dbo.STK_LOCATION WHERE LOC_CODE IN ('WH01','WH03','WH04','WH08','WH11')" & "AND LOC_STOCK_CODE = '" & stockCode & "'"
Dim strQuery3 As String = "SELECT STKLANG_STOCKNAME as [Chinese_Description] FROM dbo.STK_STOCK_LANG WHERE STKLANG_STOCKCODE ='" & stockCode & "'"
Dim strQuery4 = "SELECT STK_SELLPRICE1 as [Retail_Price], STK_SELLPRICE5 as [Retail_Rest_Split] FROM dbo.STK_STOCK_2 WHERE STKCODE2 = '" & stockCode & "'"
#dwilliss has just answered the question using parameters, which is probably better than my method. Posting this anyway

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

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