0

我有以下方法来创建一个excel文件。

Private Sub ExportToExcel()

    Dim dv As DataView = CType(SqlDataSourceExel.Select(DataSourceSelectArguments.Empty), DataView)

    Dim dt As DataTable = dv.ToTable()

    Dim query = From r In dt.AsEnumerable()
               Select New With {
                   .callid = r.Field(Of Decimal)("callid"),
                   .Problem = r.Field(Of String)("Problem"),
                   .Details = r.Field(Of String)("Details"),
                   .Entered_Date = r.Field(Of DateTime)("Entered_Date"),
                   .Name = r.Field(Of String)("Name"),
                   .comments = ""
                   }

    Dim sb As StringBuilder = New StringBuilder()
    Dim fileName As String = "list.xls"

    'sb.Append("Call Id \t Problem \t Details \t Entered_Date & \t Logged by \t Comments")

    For Each row In query
        sb.Append(row.callid & "\t" & row.Problem & "\t" & row.Details & "\t" & row.Entered_Date & "\t" & row.Name & "\t" & row.comments & "\n")

    Next

    HttpContext.Current.Response.Clear()
    HttpContext.Current.Response.ContentType = "Application/x-msexcel"
    HttpContext.Current.Response.AddHeader("content-disposition", "attachment; filename=" + fileName)
    HttpContext.Current.Response.Write(sb.ToString())
    HttpContext.Current.Response.End()

End Sub

执行代码时出现以下错误。我该如何解决?

Microsoft JScript 运行时错误:Sys.WebForms.PageRequestManagerParserErrorException:无法解析从服务器接收到的消息。

4

1 回答 1

0

您可以使用以下代码:

DataTable DtReqDetails = (DataTable)ViewState["DtReqDetails"];
        if (DtReqDetails != null)
        {
            string attachment = "attachment; filename=History.xls";
            Response.ClearContent();
            Response.AddHeader("content-disposition", attachment);
            Response.ContentType = "application/vnd.ms-excel";
            string tab = "";
            foreach (DataColumn dc in DtReqDetails.Columns)
            {
                Response.Write(tab + dc.ColumnName);
                tab = "\t";
            }
            Response.Write("\n");
            int i;
            foreach (DataRow dr in DtReqDetails.Rows)
            {
                tab = "";
                for (i = 0; i < DtReqDetails.Columns.Count; i++)
                {
                    Response.Write(tab + dr[i].ToString());
                    tab = "\t";
                }
                Response.Write("\n");
            }
            Response.End();
        }
于 2012-12-12T07:22:52.477 回答