导出网格视图数据

发布于 2024-08-03 23:47:20 字数 198 浏览 7 评论 0原文

将 gridview 导出到 Excel 电子表格的最佳方法是什么? 这看起来很简单

,只是我的 Gridview 没有导出属性。最快的方法是什么?

What is the best way to export a gridview into an Excel spreadsheet? This seems easy

except that my Gridview doesn't have an export attribute. What is the quickest way to do this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

就此别过 2024-08-10 23:47:20

可能有一些解决方案,但如果您想自己做,您可以编写一些代码来遍历 GridView.Rows 集合,然后遍历其中的 GridViewRow.Cells 集合。

从那里构建 CSV 文件应该非常容易,并且 Excel 可以毫无问题地读取它。

CSV 文件只是文本文件,其值放在引号内,并以逗号分隔。像这样:

"value", "value", "value"
"value", "value", "value"

您可以打开记事本并手动构建一个来尝试一下。

There's probably something out there for this, but if you want to do it yourself you could just write some code that walks the GridView.Rows collection, and then the GridViewRow.Cells collection inside of that.

It should be pretty easy to build a CSV file from there, and Excel could read it no problem.

CSV files are just text files with values inside of quotes, seperated by commas. Like this:

"value", "value", "value"
"value", "value", "value"

You can just pop Notepad open and build one by hand to try it out.

陌上青苔 2024-08-10 23:47:20

我已经这样做过好几次了。 Excel 有 XML 版本。它以 .xml 扩展名结束,但您只需将文件的扩展名更改为 .xls,XML 格式的文件就可以在 Excel 中打开。

这种方法的最大障碍是 Excel XML 格式。我通常以我想要的近似格式在 Excel 中创建一个 Excel 文件。然后,我将 Excel 文件保存为 XML 格式,并在文本编辑器中将其打开。

我通常从此 Excel 示例页面创建一个模板文件。然后,当我在 Gridview 中导出信息时,我只需为包含我计划填充的单元格的部分创建 xml,我只需在模板文件中添加已有的文本即可。

一旦打开 xml 格式的 Excel 文件,您就会相对容易地找出所需的 XML。最难理解的部分是单元格引用格式选项的方式,这些选项位于 XML 文件的顶部。

祝你好运,如果您需要更多说明,请告诉我。

编辑:
您只需创建一次 Excel 模板文件,即可了解您需要生成的所需 xml。生成 xml 后,使用以下代码将其发送给用户:

string fileName = "ExportedFile.xls";
Response.Clear();
Response.Buffer = true;
Response.ContentType = "text/xml";
Response.AddHeader("Content-Disposition", "attachment; filename=" + fileName);
ExportToExcel(HttpContext.Current.Response.OutputStream, testUID);
Response.End();



public static void ExportToExcel(Stream outputStream)
{
    XmlTextWriter xmlSink = new XmlTextWriter(outputStream, Encoding.Default);

    //ExcelHeaderString and ExcelStylesString are from the template
    xmlSink.WriteRaw(ExcelHeaderString);
    xmlSink.WriteRaw(ExcelStylesString);

    //write your elements here
    xmlSink.WriteElement("YourElements");

    //ExcelFooterString is from the template
    xmlSink.WriteRaw(ExcelFooterString);
}

I've done this several times. Excel has a XML version. It ends up with the .xml extension, but you can just change the file's extension to .xls and the XML formatted file will open in excel just fine.

The biggest hurdle of this approach is the excel XML format. I usually create an excel file in excel in the approximate format that I desire. I then save the Excel file to XML format, and open it up in a text editor.

I usually create a template file from this Excel sample page. Then when I am exporting the information in the Gridview, I only have to create the xml for the section that contains the cells I plan on populating, I just prepend, and append the text already in the template file.

Once you open up the xml formatted excel file, you'll figure out the needed XML relatively easily. The hardest part to understand is the way the cells reference the formatting options, which are at the top of the XML file.

Good luck, let me know if you need more clarification.

Edit:
You will only need to create the template excel file once, just to get a feel for the needed xml that you'll need to generate. Once you've generated the xml use the following code to send it to the user:

string fileName = "ExportedFile.xls";
Response.Clear();
Response.Buffer = true;
Response.ContentType = "text/xml";
Response.AddHeader("Content-Disposition", "attachment; filename=" + fileName);
ExportToExcel(HttpContext.Current.Response.OutputStream, testUID);
Response.End();



public static void ExportToExcel(Stream outputStream)
{
    XmlTextWriter xmlSink = new XmlTextWriter(outputStream, Encoding.Default);

    //ExcelHeaderString and ExcelStylesString are from the template
    xmlSink.WriteRaw(ExcelHeaderString);
    xmlSink.WriteRaw(ExcelStylesString);

    //write your elements here
    xmlSink.WriteElement("YourElements");

    //ExcelFooterString is from the template
    xmlSink.WriteRaw(ExcelFooterString);
}
羁客 2024-08-10 23:47:20

这个 .net 库非常适合我们的用例。

该库允许您使用 XML 生成 Excel 工作簿,它 100% 用 C# 构建,根本不需要安装 Excel 来生成文件。它公开了一个简单的对象模型来生成 XML 工作簿。

没有与 GridView 控件的内置集成,但编写通用适配器非常容易,并且可以在其他项目中重用。

This library for .net has worked very well for our use cases.

This library allows you to generate Excel Workbooks using XML, it is built 100% in C# and does not requires Excel installed at all to generate the files. It exposes a simple object model to generate the XML Workbooks.

There's no built-in integration with a GridView control, but writing a generic adapter is easy enough and would be reusable in other projects.

夏至、离别 2024-08-10 23:47:20

此方法直接转换为 Excel 格式,无需在服务器上安装 XML 或使用 XML。

        Protected Sub ExportToExcel()

        Dim gv1 As GridView = FindControlRecursive(objPlaceHolder, "GridView1")
        If Not gv1 Is Nothing Then
            Response.ClearHeaders()
            Response.ClearContent()

            ' Set the content type to Excel
            Response.ContentType = "application/vnd.ms-excel"

            ' make it open the save as dialog
            Response.AddHeader("content-disposition", "attachment; filename=ExcelExport.xls")

            'Turn off the view state 
            Me.EnableViewState = False

            'Remove the charset from the Content-Type header 
            Response.Charset = String.Empty

            Dim myTextWriter As New System.IO.StringWriter
            Dim myHtmlTextWriter As New System.Web.UI.HtmlTextWriter(myTextWriter)
            Dim frm As HtmlForm = New HtmlForm()
            Controls.Add(frm)
            frm.Controls.Add(gv1)

            'Get the HTML for the control 
            frm.RenderControl(myHtmlTextWriter)

            'Write the HTML to the browser 
            Response.Write(myTextWriter.ToString())
            'End the response 
            Response.End()
        End If
    End Sub

Private Function FindControlRecursive(ByVal root As Control, ByVal id As String) As Control
    If root.ID = id Then
        Return root
    End If
    Dim c As Control
    For Each c In root.Controls
        Dim t As Control = FindControlRecursive(c, id)
        If Not t Is Nothing Then
            Return t
        End If
    Next
    Return Nothing
End Function

This method goes straight into Excel format without requiring XML be installed on the server or by using XML.

        Protected Sub ExportToExcel()

        Dim gv1 As GridView = FindControlRecursive(objPlaceHolder, "GridView1")
        If Not gv1 Is Nothing Then
            Response.ClearHeaders()
            Response.ClearContent()

            ' Set the content type to Excel
            Response.ContentType = "application/vnd.ms-excel"

            ' make it open the save as dialog
            Response.AddHeader("content-disposition", "attachment; filename=ExcelExport.xls")

            'Turn off the view state 
            Me.EnableViewState = False

            'Remove the charset from the Content-Type header 
            Response.Charset = String.Empty

            Dim myTextWriter As New System.IO.StringWriter
            Dim myHtmlTextWriter As New System.Web.UI.HtmlTextWriter(myTextWriter)
            Dim frm As HtmlForm = New HtmlForm()
            Controls.Add(frm)
            frm.Controls.Add(gv1)

            'Get the HTML for the control 
            frm.RenderControl(myHtmlTextWriter)

            'Write the HTML to the browser 
            Response.Write(myTextWriter.ToString())
            'End the response 
            Response.End()
        End If
    End Sub

Private Function FindControlRecursive(ByVal root As Control, ByVal id As String) As Control
    If root.ID = id Then
        Return root
    End If
    Dim c As Control
    For Each c In root.Controls
        Dim t As Control = FindControlRecursive(c, id)
        If Not t Is Nothing Then
            Return t
        End If
    Next
    Return Nothing
End Function
走走停停 2024-08-10 23:47:20

我使用了 CarlosAg.ExcelXmlWriter 链接

我循环遍历所有 GridViews HeaderCells,然后遍历所有行。唯一的事情是,如果您允许分页并且您有多个页面,则必须将 PageSize 设置为较高的值(我设置为 10000000),然后将 DataBindGridView 再次完成你的工作。然后设置旧的 PageSize 值。如果有人知道更好的解决方案,欢迎您。

编辑: try/catch 之所以存在,是因为由于某种原因无法检查控件类型,然后转换为 Label 或 LinkBut​​ton ==> control.GetType()。

这是我的代码。

 public static Workbook CreateWorkbook(GridView gridView)
    {
        int pageSize = gridView.PageSize;
        gridView.PageSize = 10000000;
        gridView.DataBind();

        Workbook workbook = new Workbook();
        Worksheet sheet = workbook.Worksheets.Add("Export");

        WorksheetStyle style = workbook.Styles.Add("headerStyle");
        style.Font.Bold = true;
        style = workbook.Styles.Add("defaultStyle");
        style.Alignment.WrapText = true;
        style = workbook.Styles.Add("infoStyle");
        style.Font.Color = "Red";
        style.Font.Bold = true;

        sheet.Table.Rows.Add(new WorksheetRow());

        WorksheetRow headerRow = new WorksheetRow();
        foreach (DataControlFieldHeaderCell cell in gridView.HeaderRow.Cells)
        {
            if (!string.IsNullOrEmpty(cell.Text))
                headerRow.Cells.Add(cell.Text, DataType.String, "headerStyle");
            else
                foreach (Control control in cell.Controls)
                {
                    LinkButton linkButton = new LinkButton();
                    try
                    {
                        linkButton = (LinkButton)control;
                    }
                    catch { }

                    if (!string.IsNullOrEmpty(linkButton.Text))
                        headerRow.Cells.Add(linkButton.Text, DataType.String, "headerStyle");
                    else
                    {
                        Label label = new Label();
                        try
                        {
                            label = (Label)control;
                        }
                        catch { }
                        if (!string.IsNullOrEmpty(label.Text))
                            headerRow.Cells.Add(label.Text, DataType.String, "headerStyle");
                    }
                }
        }

        sheet.Table.Rows.Add(headerRow);

        foreach (GridViewRow row in gridView.Rows)
        {
            WorksheetRow wrow = new WorksheetRow();
            foreach (TableCell cell in row.Cells)
            {
                foreach (Control control in cell.Controls)
                {
                    if (control.GetType() == typeof(Label))
                    {
                        wrow.Cells.Add(((Label)control).Text, DataType.String, "defaultStyle");
                    }
                }
            }
            sheet.Table.Rows.Add(wrow);
        }

        gridView.PageSize = pageSize;

        return workbook;
    }

I used CarlosAg.ExcelXmlWriter link.

I looped through all GridViews HeaderCells and then through all rows. The only thing is that if you allow paging and you've more than one page you have to set the PageSize to a high value (I set to 10000000) then DataBind the GridView again and do your work. Afterwards set the old PageSize value back. If someone knows a better solution, you're welcome.

EDIT: The try/catch is there because for some reason it is not possible to check the control type and then cast to Label or LinkButton ==> control.GetType().

Here's my code.

 public static Workbook CreateWorkbook(GridView gridView)
    {
        int pageSize = gridView.PageSize;
        gridView.PageSize = 10000000;
        gridView.DataBind();

        Workbook workbook = new Workbook();
        Worksheet sheet = workbook.Worksheets.Add("Export");

        WorksheetStyle style = workbook.Styles.Add("headerStyle");
        style.Font.Bold = true;
        style = workbook.Styles.Add("defaultStyle");
        style.Alignment.WrapText = true;
        style = workbook.Styles.Add("infoStyle");
        style.Font.Color = "Red";
        style.Font.Bold = true;

        sheet.Table.Rows.Add(new WorksheetRow());

        WorksheetRow headerRow = new WorksheetRow();
        foreach (DataControlFieldHeaderCell cell in gridView.HeaderRow.Cells)
        {
            if (!string.IsNullOrEmpty(cell.Text))
                headerRow.Cells.Add(cell.Text, DataType.String, "headerStyle");
            else
                foreach (Control control in cell.Controls)
                {
                    LinkButton linkButton = new LinkButton();
                    try
                    {
                        linkButton = (LinkButton)control;
                    }
                    catch { }

                    if (!string.IsNullOrEmpty(linkButton.Text))
                        headerRow.Cells.Add(linkButton.Text, DataType.String, "headerStyle");
                    else
                    {
                        Label label = new Label();
                        try
                        {
                            label = (Label)control;
                        }
                        catch { }
                        if (!string.IsNullOrEmpty(label.Text))
                            headerRow.Cells.Add(label.Text, DataType.String, "headerStyle");
                    }
                }
        }

        sheet.Table.Rows.Add(headerRow);

        foreach (GridViewRow row in gridView.Rows)
        {
            WorksheetRow wrow = new WorksheetRow();
            foreach (TableCell cell in row.Cells)
            {
                foreach (Control control in cell.Controls)
                {
                    if (control.GetType() == typeof(Label))
                    {
                        wrow.Cells.Add(((Label)control).Text, DataType.String, "defaultStyle");
                    }
                }
            }
            sheet.Table.Rows.Add(wrow);
        }

        gridView.PageSize = pageSize;

        return workbook;
    }
如果没有 2024-08-10 23:47:20
Private exportToExcel As Boolean = False

Private Sub LoadInExcel()
    Me.Response.ClearContent()
    Me.Response.AddHeader("content-disposition", "attachment; filename=MyFile.xls")
    Me.Response.ContentType = "application/ms-excel"
    Dim sw1 As New IO.StringWriter
    Dim htw1 As HtmlTextWriter = New HtmlTextWriter(sw1)
    GridView1.RenderControl(htw1)
    Response.Write(sw1.ToString())
    Response.End()
End Sub

Public Overrides Sub VerifyRenderingInServerForm(ByVal control As Control)
    ' Confirms that an HtmlForm control is rendered for the specified ASP.NET
    ' server control at run time.
End Sub

Protected Overrides Sub Render(ByVal writer As System.Web.UI.HtmlTextWriter)
    If exportToExcel Then
        LoadInExcel()
    End If

    MyBase.Render(writer)
End Sub

Protected Sub btnPrint_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnPrint.Click
    exportToExcel = True
End Sub

您必须安装 Excel 并在项目中引用 Office 互操作库。
添加:

导入Microsoft.Office.Core,
导入 Microsoft.Office.Interop

上面的解决方案采用 gridview 并从中提取 html。然后写入excel。来自网格的 html 将包含样式属性,例如 padding 和 padding 等。颜色。它还将使可排序的列标题看起来像链接。当我使用它时,我编写了一个自定义解析器来去除所有不需要的样式,只为我提供原始数据。我将把这个任务留给你,因为它是特定于每个网格的。

包含对VerifyRenderingInServerForm 的覆盖非常重要,即使其中没​​有任何代码。

Private exportToExcel As Boolean = False

Private Sub LoadInExcel()
    Me.Response.ClearContent()
    Me.Response.AddHeader("content-disposition", "attachment; filename=MyFile.xls")
    Me.Response.ContentType = "application/ms-excel"
    Dim sw1 As New IO.StringWriter
    Dim htw1 As HtmlTextWriter = New HtmlTextWriter(sw1)
    GridView1.RenderControl(htw1)
    Response.Write(sw1.ToString())
    Response.End()
End Sub

Public Overrides Sub VerifyRenderingInServerForm(ByVal control As Control)
    ' Confirms that an HtmlForm control is rendered for the specified ASP.NET
    ' server control at run time.
End Sub

Protected Overrides Sub Render(ByVal writer As System.Web.UI.HtmlTextWriter)
    If exportToExcel Then
        LoadInExcel()
    End If

    MyBase.Render(writer)
End Sub

Protected Sub btnPrint_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnPrint.Click
    exportToExcel = True
End Sub

You must have excel installed and reference the Office interop libraries in your project.
Add:

Imports Microsoft.Office.Core,
Imports Microsoft.Office.Interop

The solution above takes the gridview and pulls the html out of it. Then writes it to excel. The html coming from the grid will include style attributes such as padding & color. It will also make sortable column headings look like links. When I used this I wrote a custom parser to strip all the unwanted styling out to give me just the raw data. I will leave that task up to you since it is specific to each grid.

It is very important that you include the override to VerifyRenderingInServerForm, even though there is not any code inside of it.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文