我使用下面的代码使用EPPlus将数据表中的记录导出到excel文件。
Dim excelPackage = New ExcelPackage
Dim excelWorksheet = excelPackage.Workbook.Worksheets.Add("DemoPage")
excelWorksheet.Cells("A1").LoadFromDataTable(dt, True)
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
Response.AddHeader("content-disposition", "attachment; filename=ExcelDemo.xlsx")
Response.BinaryWrite(excelPackage.GetAsByteArray())
Response.End()
然而,在遍历代码块后,在Response.End(),我得到一个异常 {属性评估失败。}
更新
错误日志是:
ERROR: System.Threading.ThreadAbortException: Thread was being aborted.
at System.Threading.Thread.AbortInternal()
at System.Threading.Thread.Abort(Object stateInfo)
at System.Web.HttpResponse.End()
at Reporting.Page_Load(Object sender, EventArgs e) in C:\Reporting.aspx.vb:line 38
知道可能导致这种情况的原因吗?
答案 0 :(得分:2)
删除 Response.End()行并编写以下代码:
HttpContext.Current.Response.Clear()
Response.ClearHeaders()
Response.Buffer = True
Dim excelPackage = New ExcelPackage
Dim excelWorksheet = excelPackage.Workbook.Worksheets.Add("DemoPage")
excelWorksheet.Cells("A1").LoadFromDataTable(dt, True)
Response.ContentType = "application/vnd.openxmlformats-
officedocument.spreadsheetml.sheet"
Response.AddHeader("content-disposition", "attachment; filename=ExcelDemo.xlsx")
Response.Charset = ""
Response.BinaryWrite(excelPackage.GetAsByteArray())
Response.Flush()
Response.Close()
excelPackage.close() or
excelPackage=nothing or excelPackage.dispose() whichever is fit.
hope you will not get "Property Evaluation Error"
答案 1 :(得分:0)
注意:
在本地计算机上测试下载文件时不要使用 Response.End(); 否则可能会引发错误。
但是添加 到Response.End() 当在服务器中部署相同的代码并从客户端计算机测试相同的代码时。 在这种情况下不会引发错误。
删除Response.Charset =“”