【发布时间】:2023-03-08 04:12:02
【问题描述】:
我在 Asp.net 中有一个网站,其中我实现了一个以 Excel 格式存储 GridView 的按钮,但是当我打开文件时,我无法看到 GridView 的实际内容,我只能看到列标题。通过 NuGet 包管理器安装 EPPlus 后,我使用了以下三个导入。
using OfficeOpenXml;
using System.IO;
using WebFormsTest.Models;
我后面的代码如下
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
If Not IsPostBack Then
Dim GetProducts As Object = Nothing
GridView6.DataSource = GetProducts
GridView6.DataBind()
End If
End Sub
Protected Sub Button3_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Button3.Click
Response.Clear()
Dim products = GetProducts()
GridView6.DataSource = products
GridView6.DataBind()
Dim excel As ExcelPackage = New ExcelPackage
Dim workSheet = excel.Workbook.Worksheets.Add("Products")
Dim totalCols = GridView6.Rows(0).Cells.Count
Dim totalRows = GridView6.Rows.Count
Dim headerRow = GridView6.HeaderRow
worksheet.Cells["A1"].LoadFromCollection(GetProducts())
Dim memoryStream = New MemoryStream
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
Response.AddHeader("content-disposition", "attachment; filename=products.xlsx")
excel.SaveAs(memoryStream)
memoryStream.WriteTo(Response.OutputStream)
Response.Flush()
Response.End()
End Sub
Public Function GetProducts() As List(Of Product)
End Function
我的 Aspx 按钮如下所示
<asp:Button ID="Button3" runat="server" Text="EXPORT RTD TO EXCEL" onclick="Button3_Click" BackColor="#FF9966" CssClass="btn btn-large" Font-Bold="True"/>
【问题讨论】:
标签: asp.net excel vb.net gridview