我有 2 个代码块,如果有人可以帮助我将它们组合在一起,我将获得我正在寻找的功能。第一个代码块使用我正在寻找的下载对话框将 gridview 下载到 excel:
Public Overloads Overrides Sub VerifyRenderingInServerForm(ByVal control As Control)
' Verifies that the control is rendered
End Sub
Private Sub ExportToExcel(ByVal filename As String, ByVal gv As GridView, ByVal numOfCol As Integer)
Response.Clear()
Response.Buffer = True
Response.AddHeader("content-disposition", String.Format("attachment; filename={0}", filename))
Response.Charset = ""
Response.ContentType = "application/vnd.ms-excel"
Dim sw As New StringWriter()
Dim hw As New HtmlTextWriter(sw)
gv.AllowPaging = False
gv.DataBind()
'Change the Header Row back to white color
gv.HeaderRow.Style.Add("background-color", "#FFFFFF")
For i As Integer = 0 To numOfCol - 1
gv.HeaderRow.Cells(i).Style.Add("background-color", "blue")
gv.HeaderRow.Cells(i).Style.Add("color", "#FFFFFF")
Next
For i As Integer = 0 To gv.Rows.Count - 1
Dim row As GridViewRow = gv.Rows(i)
'Change Color back to white
row.BackColor = System.Drawing.Color.White
For j As Integer = 0 To numOfCol - 1
row.Cells(j).Style.Add("text-align", "center")
Next
'Apply text style to each Row
row.Attributes.Add("class", "textmode")
'Apply style to Individual Cells of Alternating Row
If i Mod 2 <> 0 Then
For j As Integer = 0 To numOfCol - 1
row.Cells(j).Style.Add("background-color", "#CCFFFF")
row.Cells(j).Style.Add("text-align", "center")
'#C2D69B
'row.Cells(j).Style.Add("font-size", "12pt")
Next
End If
Next
gv.RenderControl(hw)
'style to format numbers to string
Dim style As String = "<style> .textmode { mso-number-format:\@; } </style>"
Response.Write(style)
Response.Output.Write(sw.ToString())
Response.Flush()
Response.End()
End Sub
第二段代码是我希望下载的示例报告。因此,我希望此函数能够接受工作表对象,而不是下载 gridview。
评论 Frank 的建议... 弗兰克感谢您的帮助,这几乎对我有用。问题是如果我的根文件夹中没有名为 test.xls 的虚拟文件,代码就会崩溃。当我把它放在那里时,它会加载 2 个工作簿 test.xls[1] 和 Book 2,其中 test.xls 是一个空白工作簿,Book 2 是正确的动态创建的报告。我不想将此文件保存在根文件夹中(如果我没有的话),我希望用户只需打开或将其下载到他们的客户端即可。创建 woorkbook 后我使用的代码是...... Dim fn As String = "RptCrd_ "& "BUNDLE"& ".xls" Dim eio As String = "~/ContentDisposition/"& fn
Dim exData As Byte() = File.ReadAllBytes(Server.MapPath(eio))
Response.AddHeader("content-disposition", String.Format("attachment; filename={0}", fn))
Response.ContentType = "application/x-msexcel"
Response.BinaryWrite(exData)
Response.Flush()
Response.End()
releaseObject(xlApp)
releaseObject(xlWorkBook)
最佳答案
也许您需要将正确的内容类型和 header 添加到您的响应中,以便浏览器知道您要使用 Excel 处理下载。您可能会将其放在 Response.Write(style); 之后打电话。
尝试使用谷歌搜索 MS Excel mime 类型,以及如何将格式正确的标题和内容类型添加到您的响应中。
我只是将一些代码放在一起,将下载内容输出到浏览器,以便它可以将其作为 Excel 电子表格进行处理。这应该为您提供如何格式化响应 header 的示例。
这只是读取现有电子表格,然后将其提供给响应流。这只是演示如何制定响应 header 。
byte[] excelData = File.ReadAllBytes(Server.MapPath("test.xls"));
Response.AddHeader("Content-Disposition", "attachment; filename=test.xls");
Response.ContentType = "application/x-msexcel";
Response.BinaryWrite(excelData);
关于c# - 使动态创建的 Excel 报告可下载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2585963/