将 LINQ 对象列表导出到 Excel 文件

发布于 2024-10-12 12:12:29 字数 69 浏览 2 评论 0原文

在 Web 应用程序中,是否有一种简单的方法可以将 LINQ 对象列表导出到 Excel 文件?有没有好的库可以做到这一点?

From a web application, is there a simple way to export a list of LINQ objects to an Excel file? Are there any good libraries that can do this?

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

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

发布评论

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

评论(3

笑梦风尘 2024-10-19 12:12:29

这是我根据上面 VB 视频的链接最终得到的 Excel 导出。它接受任何对象列表(不包括实体框架对象上的导航属性和集合)并将其导出到 Excel。它在约 4 秒内导出约 35K 记录。

public void ExportToExcel<T>(List<T> list)
    {
        int columnCount = 0;

        DateTime StartTime = DateTime.Now;

        StringBuilder rowData = new StringBuilder();

        PropertyInfo[] properties = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);

        rowData.Append("<Row ss:StyleID=\"s62\">");
        foreach (PropertyInfo p in properties)
        {
            if (p.PropertyType.Name != "EntityCollection`1" && p.PropertyType.Name != "EntityReference`1" && p.PropertyType.Name != p.Name)
            {
                columnCount++;
                rowData.Append("<Cell><Data ss:Type=\"String\">" + p.Name + "</Data></Cell>");
            }
            else
                break;

        }
        rowData.Append("</Row>");

        foreach (T item in list)
        {                
            rowData.Append("<Row>");
            for (int x = 0; x < columnCount; x++) //each (PropertyInfo p in properties)
            {                    
                object o = properties[x].GetValue(item, null);
                string value = o == null ? "" : o.ToString();                    
                rowData.Append("<Cell><Data ss:Type=\"String\">" + value + "</Data></Cell>");

            }
            rowData.Append("</Row>");
        }

        var sheet = @"<?xml version=""1.0""?>
                    <?mso-application progid=""Excel.Sheet""?>
                    <Workbook xmlns=""urn:schemas-microsoft-com:office:spreadsheet""
                        xmlns:o=""urn:schemas-microsoft-com:office:office""
                        xmlns:x=""urn:schemas-microsoft-com:office:excel""
                        xmlns:ss=""urn:schemas-microsoft-com:office:spreadsheet""
                        xmlns:html=""http://www.w3.org/TR/REC-html40"">
                        <DocumentProperties xmlns=""urn:schemas-microsoft-com:office:office"">
                            <Author>MSADMIN</Author>
                            <LastAuthor>MSADMIN</LastAuthor>
                            <Created>2011-07-12T23:40:11Z</Created>
                            <Company>Microsoft</Company>
                            <Version>12.00</Version>
                        </DocumentProperties>
                        <ExcelWorkbook xmlns=""urn:schemas-microsoft-com:office:excel"">
                            <WindowHeight>6600</WindowHeight>
                            <WindowWidth>12255</WindowWidth>
                            <WindowTopX>0</WindowTopX>
                            <WindowTopY>60</WindowTopY>
                            <ProtectStructure>False</ProtectStructure>
                            <ProtectWindows>False</ProtectWindows>
                        </ExcelWorkbook>
                        <Styles>
                            <Style ss:ID=""Default"" ss:Name=""Normal"">
                                <Alignment ss:Vertical=""Bottom""/>
                                <Borders/>
                                <Font ss:FontName=""Calibri"" x:Family=""Swiss"" ss:Size=""11"" ss:Color=""#000000""/>
                                <Interior/>
                                <NumberFormat/>
                                <Protection/>
                            </Style>
                            <Style ss:ID=""s62"">
                                <Font ss:FontName=""Calibri"" x:Family=""Swiss"" ss:Size=""11"" ss:Color=""#000000""
                                    ss:Bold=""1""/>
                            </Style>
                        </Styles>
                        <Worksheet ss:Name=""Sheet1"">
                            <Table ss:ExpandedColumnCount=""" + (properties.Count() + 1) + @""" ss:ExpandedRowCount=""" + (list.Count() + 1) + @""" x:FullColumns=""1""
                                x:FullRows=""1"" ss:DefaultRowHeight=""15"">
                                " + rowData.ToString() +@"
                            </Table>
                            <WorksheetOptions xmlns=""urn:schemas-microsoft-com:office:excel"">
                                <PageSetup>
                                    <Header x:Margin=""0.3""/>
                                    <Footer x:Margin=""0.3""/>
                                    <PageMargins x:Bottom=""0.75"" x:Left=""0.7"" x:Right=""0.7"" x:Top=""0.75""/>
                                </PageSetup>
                                <Print>
                                    <ValidPrinterInfo/>
                                    <HorizontalResolution>300</HorizontalResolution>
                                    <VerticalResolution>300</VerticalResolution>
                                </Print>
                                <Selected/>
                                <Panes>
                                    <Pane>
                                        <Number>3</Number>
                                        <ActiveCol>2</ActiveCol>
                                    </Pane>
                                </Panes>
                                <ProtectObjects>False</ProtectObjects>
                                <ProtectScenarios>False</ProtectScenarios>
                            </WorksheetOptions>
                        </Worksheet>
                        <Worksheet ss:Name=""Sheet2"">
                            <Table ss:ExpandedColumnCount=""1"" ss:ExpandedRowCount=""1"" x:FullColumns=""1""
                                x:FullRows=""1"" ss:DefaultRowHeight=""15"">
                            </Table>
                            <WorksheetOptions xmlns=""urn:schemas-microsoft-com:office:excel"">
                                <PageSetup>
                                    <Header x:Margin=""0.3""/>
                                    <Footer x:Margin=""0.3""/>
                                    <PageMargins x:Bottom=""0.75"" x:Left=""0.7"" x:Right=""0.7"" x:Top=""0.75""/>
                                </PageSetup>
                                <ProtectObjects>False</ProtectObjects>
                                <ProtectScenarios>False</ProtectScenarios>
                            </WorksheetOptions>
                        </Worksheet>
                        <Worksheet ss:Name=""Sheet3"">
                            <Table ss:ExpandedColumnCount=""1"" ss:ExpandedRowCount=""1"" x:FullColumns=""1""
                                x:FullRows=""1"" ss:DefaultRowHeight=""15"">
                            </Table>
                            <WorksheetOptions xmlns=""urn:schemas-microsoft-com:office:excel"">
                                <PageSetup>
                                    <Header x:Margin=""0.3""/>
                                    <Footer x:Margin=""0.3""/>
                                    <PageMargins x:Bottom=""0.75"" x:Left=""0.7"" x:Right=""0.7"" x:Top=""0.75""/>
                                </PageSetup>
                                <ProtectObjects>False</ProtectObjects>
                                <ProtectScenarios>False</ProtectScenarios>
                            </WorksheetOptions>
                        </Worksheet>
                    </Workbook>";

        System.Diagnostics.Debug.Print(StartTime.ToString() + " - " + DateTime.Now);
        System.Diagnostics.Debug.Print((DateTime.Now - StartTime).ToString());

        string attachment = "attachment; filename=Report.xml";
        HttpContext.Current.Response.ClearContent();
        HttpContext.Current.Response.AddHeader("content-disposition", attachment);
        HttpContext.Current.Response.Write(sheet);
        HttpContext.Current.Response.ContentType = "application/ms-excel";
        HttpContext.Current.Response.End();

    }

This is the Excel Export I ended up with based on the link to the VB video above. It takes any List of Objects (It excludes navigation properties and collections on Entity Framework objects) and exports them to Excel. It exports about 35K records in ~4 seconds.

public void ExportToExcel<T>(List<T> list)
    {
        int columnCount = 0;

        DateTime StartTime = DateTime.Now;

        StringBuilder rowData = new StringBuilder();

        PropertyInfo[] properties = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);

        rowData.Append("<Row ss:StyleID=\"s62\">");
        foreach (PropertyInfo p in properties)
        {
            if (p.PropertyType.Name != "EntityCollection`1" && p.PropertyType.Name != "EntityReference`1" && p.PropertyType.Name != p.Name)
            {
                columnCount++;
                rowData.Append("<Cell><Data ss:Type=\"String\">" + p.Name + "</Data></Cell>");
            }
            else
                break;

        }
        rowData.Append("</Row>");

        foreach (T item in list)
        {                
            rowData.Append("<Row>");
            for (int x = 0; x < columnCount; x++) //each (PropertyInfo p in properties)
            {                    
                object o = properties[x].GetValue(item, null);
                string value = o == null ? "" : o.ToString();                    
                rowData.Append("<Cell><Data ss:Type=\"String\">" + value + "</Data></Cell>");

            }
            rowData.Append("</Row>");
        }

        var sheet = @"<?xml version=""1.0""?>
                    <?mso-application progid=""Excel.Sheet""?>
                    <Workbook xmlns=""urn:schemas-microsoft-com:office:spreadsheet""
                        xmlns:o=""urn:schemas-microsoft-com:office:office""
                        xmlns:x=""urn:schemas-microsoft-com:office:excel""
                        xmlns:ss=""urn:schemas-microsoft-com:office:spreadsheet""
                        xmlns:html=""http://www.w3.org/TR/REC-html40"">
                        <DocumentProperties xmlns=""urn:schemas-microsoft-com:office:office"">
                            <Author>MSADMIN</Author>
                            <LastAuthor>MSADMIN</LastAuthor>
                            <Created>2011-07-12T23:40:11Z</Created>
                            <Company>Microsoft</Company>
                            <Version>12.00</Version>
                        </DocumentProperties>
                        <ExcelWorkbook xmlns=""urn:schemas-microsoft-com:office:excel"">
                            <WindowHeight>6600</WindowHeight>
                            <WindowWidth>12255</WindowWidth>
                            <WindowTopX>0</WindowTopX>
                            <WindowTopY>60</WindowTopY>
                            <ProtectStructure>False</ProtectStructure>
                            <ProtectWindows>False</ProtectWindows>
                        </ExcelWorkbook>
                        <Styles>
                            <Style ss:ID=""Default"" ss:Name=""Normal"">
                                <Alignment ss:Vertical=""Bottom""/>
                                <Borders/>
                                <Font ss:FontName=""Calibri"" x:Family=""Swiss"" ss:Size=""11"" ss:Color=""#000000""/>
                                <Interior/>
                                <NumberFormat/>
                                <Protection/>
                            </Style>
                            <Style ss:ID=""s62"">
                                <Font ss:FontName=""Calibri"" x:Family=""Swiss"" ss:Size=""11"" ss:Color=""#000000""
                                    ss:Bold=""1""/>
                            </Style>
                        </Styles>
                        <Worksheet ss:Name=""Sheet1"">
                            <Table ss:ExpandedColumnCount=""" + (properties.Count() + 1) + @""" ss:ExpandedRowCount=""" + (list.Count() + 1) + @""" x:FullColumns=""1""
                                x:FullRows=""1"" ss:DefaultRowHeight=""15"">
                                " + rowData.ToString() +@"
                            </Table>
                            <WorksheetOptions xmlns=""urn:schemas-microsoft-com:office:excel"">
                                <PageSetup>
                                    <Header x:Margin=""0.3""/>
                                    <Footer x:Margin=""0.3""/>
                                    <PageMargins x:Bottom=""0.75"" x:Left=""0.7"" x:Right=""0.7"" x:Top=""0.75""/>
                                </PageSetup>
                                <Print>
                                    <ValidPrinterInfo/>
                                    <HorizontalResolution>300</HorizontalResolution>
                                    <VerticalResolution>300</VerticalResolution>
                                </Print>
                                <Selected/>
                                <Panes>
                                    <Pane>
                                        <Number>3</Number>
                                        <ActiveCol>2</ActiveCol>
                                    </Pane>
                                </Panes>
                                <ProtectObjects>False</ProtectObjects>
                                <ProtectScenarios>False</ProtectScenarios>
                            </WorksheetOptions>
                        </Worksheet>
                        <Worksheet ss:Name=""Sheet2"">
                            <Table ss:ExpandedColumnCount=""1"" ss:ExpandedRowCount=""1"" x:FullColumns=""1""
                                x:FullRows=""1"" ss:DefaultRowHeight=""15"">
                            </Table>
                            <WorksheetOptions xmlns=""urn:schemas-microsoft-com:office:excel"">
                                <PageSetup>
                                    <Header x:Margin=""0.3""/>
                                    <Footer x:Margin=""0.3""/>
                                    <PageMargins x:Bottom=""0.75"" x:Left=""0.7"" x:Right=""0.7"" x:Top=""0.75""/>
                                </PageSetup>
                                <ProtectObjects>False</ProtectObjects>
                                <ProtectScenarios>False</ProtectScenarios>
                            </WorksheetOptions>
                        </Worksheet>
                        <Worksheet ss:Name=""Sheet3"">
                            <Table ss:ExpandedColumnCount=""1"" ss:ExpandedRowCount=""1"" x:FullColumns=""1""
                                x:FullRows=""1"" ss:DefaultRowHeight=""15"">
                            </Table>
                            <WorksheetOptions xmlns=""urn:schemas-microsoft-com:office:excel"">
                                <PageSetup>
                                    <Header x:Margin=""0.3""/>
                                    <Footer x:Margin=""0.3""/>
                                    <PageMargins x:Bottom=""0.75"" x:Left=""0.7"" x:Right=""0.7"" x:Top=""0.75""/>
                                </PageSetup>
                                <ProtectObjects>False</ProtectObjects>
                                <ProtectScenarios>False</ProtectScenarios>
                            </WorksheetOptions>
                        </Worksheet>
                    </Workbook>";

        System.Diagnostics.Debug.Print(StartTime.ToString() + " - " + DateTime.Now);
        System.Diagnostics.Debug.Print((DateTime.Now - StartTime).ToString());

        string attachment = "attachment; filename=Report.xml";
        HttpContext.Current.Response.ClearContent();
        HttpContext.Current.Response.AddHeader("content-disposition", attachment);
        HttpContext.Current.Response.Write(sheet);
        HttpContext.Current.Response.ContentType = "application/ms-excel";
        HttpContext.Current.Response.End();

    }
耀眼的星火 2024-10-19 12:12:29

查看从 ASP.Net 链接的 VB 团队的视频,Beth Massi 实际上做了一个非常类似的演示,可能可以满足您的需求:

http://www.asp.net/linq/videos/how-do-i-create-excel-spreadsheets-using -linq-to-xml

您可能会发现同系列中的其他内容很有用,它们位于页面下方约 4/5 处:

http://www.asp.net/web-forms/data

这里还有一个名为 Linq-To-Excel 的项目 - http://code.google.com/p/linqtoexcel/

或者您可以使用 OpenXML 库来执行此类操作,这是一个这样的示例 - http://msdn。 microsoft.com/en-us/library/bb508943(v=office.12).aspx

Excel 还可以直接打开 XML 文件,因此您只需使用 XML 序列化或任何其他方法创建 XML 输出,然后打开在 Excel 中。

Check out the VB team's videos linked from the ASP.Net, Beth Massi actually does a very similar demo that might do what you want:

http://www.asp.net/linq/videos/how-do-i-create-excel-spreadsheets-using-linq-to-xml

You might find others in the same series useful, they are here about 4/5 down the page:

http://www.asp.net/web-forms/data

There is also a project called Linq-To-Excel which is here - http://code.google.com/p/linqtoexcel/

Or you could use the OpenXML libraries to do this sort of thing, here is one such example - http://msdn.microsoft.com/en-us/library/bb508943(v=office.12).aspx

Excel can also open XML files directly, so you could just create an XML output using XML serialisation or whatever other method, and open it in Excel.

拥抱我好吗 2024-10-19 12:12:29

因此,在指定 Excel 时,您将致力于行/列范例(例如,与 xml 相反)。因此,您必须指定属性如何映射到列。

除此之外,您还可以使用 Ole DB 提供程序。循环遍历您的对象,使用字符串生成器为每个对象生成一条 INSERT 语句,然后针对您的工作表执行该语句。像蛋糕一样简单。

So, in specifying Excel, you're committing to a row / column paradigm (as opposed to xml, for example). So you'll have to specify how the properties map to columns.

Beyond that you write to an Excel file using the Ole DB provider. Loop through your objects, generating an INSERT statement for each one using a stringbuilder, and execute that against your sheet. Easy as cake.

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