日期:2014-05-18  浏览次数:20497 次

生成EXCEL时保存的怎么都是网页源代码?(附代码)
我用Response.ContentType = "application/vnd.ms-excel"生成的EXCEL打开后EXCEL中怎么全都是网页源代码啊,大家帮忙看看怎么解决,源代码如下:
printBook.vb

Imports System.Data.SqlClient
Public Class printBook
  Inherits System.Web.UI.Page
  Dim conn As SqlConnection
  Private connectionstring As String
  Dim strSql As String
  Dim sda As SqlDataAdapter
  Protected WithEvents btnprint As System.Web.UI.HtmlControls.HtmlInputButton
  Protected WithEvents test As System.Web.UI.WebControls.Panel
  Dim ds As DataSet

#Region " Web 窗体设计器生成的代码 "

  '该调用是 Web 窗体设计器所必需的。
  <System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()

  End Sub
  Protected WithEvents lblTemp As System.Web.UI.WebControls.Label
  Protected WithEvents ltoolbar As System.Web.UI.WebControls.Label
  Protected WithEvents file As System.Web.UI.WebControls.Label

  '注意: 以下占位符声明是 Web 窗体设计器所必需的。
  '不要删除或移动它。
  Private designerPlaceholderDeclaration As System.Object

  Private Sub Page_Init(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Init
  'CODEGEN: 此方法调用是 Web 窗体设计器所必需的
  '不要使用代码编辑器修改它。
  InitializeComponent()
  End Sub

#End Region

  Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
  '在此处放置初始化页的用户代码
  connectionstring = System.Configuration.ConfigurationSettings.AppSettings("ConnString").ToString.Trim
  conn = New SqlConnection(connectionstring)
  '"<a onclick=window.print() style='cursor:hand'>打印该页</a>"
  file.Text = "<a href='javascript:printbook()'>生成并下载Excel文件</a>"
  End Sub
  Public Sub toprint()
  strSql = Session("urlSql")
  If strSql = "" Then
  Response.Write("<script>alert('出错了,没有传入任何参数!');window.close();</script>")
  Exit Sub
  End If
  Try
  If conn.State = ConnectionState.Open Then
  conn.Close()
  End If
  conn.Open()
  sda = New SqlDataAdapter(strSql, conn)
  ds = New DataSet
  sda.Fill(ds, "book")
  Dim i As Integer
  If ds.Tables("book").Rows.Count = 0 Then
  Response.Write("<tr><td width='100%'>今天没有录入任何数据!</p></td></tr>")
  Else
  For i = 0 To ds.Tables("book").Rows.Count - 1
  Response.Write("<tr>")
  Response.Write("<td width='70%'>" & ds.Tables("book").Rows(i)(1) & "</td>")
  Response.Write("<td width='30%' rowspan='2'>" & ds.Tables("book").Rows(i)(0) & "<td>")
  Response.Write("</tr>")
  Response.Write("<tr>")
  Response.Write("<td>" & ds.Tables("book").Rows(i)(2) & "<td>")
  Next
  End If
  Catch ex As Exception
  Server.Transfer("../../inc/err.aspx?msg=" & ex.M