简体   繁体   English

保存清单 <T> 或IQueryable <T> 到Excel-C#

[英]Save IList<T> or IQueryable<T> to Excel - C#

I'm generating a report via Linq to SQL and displaying it on the website. 我正在通过Linq to SQL生成报告,并将其显示在网站上。

I need to save the report in MS Excel (or .csv) and email it to user. 我需要将报告保存在MS Excel(或.csv)中,然后通过电子邮件发送给用户。

Any ideas on how to save it as Excel or .csv ? 关于如何将其另存为Excel或.csv的任何想法?

.NET 3.5 / C# .NET 3.5 / C#

EDIT: 编辑:

the Gridview hack works perfect. Gridview黑客作品完美。 If you use AJAX on the page, make sure you add a PostBaseTrigger to your Update Panel to cause FULL POSTBACK, it won't work otherwise. 如果您在页面上使用AJAX,请确保将PostBaseTrigger添加到更新面板以引起FULL POSTBACK,否则它将无法正常工作。

 <asp:UpdatePanel ID="UpdatePanel1" runat="server"> <ContentTemplate> <asp:Button ID="Button1" runat="server" Text="Export Grid" onclick="Button1_Click" /> </ContentTemplate> <Triggers> <asp:PostBackTrigger ControlID="Button1" /> </Triggers> </asp:UpdatePanel> 

I've also found a Library to Generate Excel XML Workbooks in .NET , however it's not as simple as accepted solution. 我还找到了.NET中生成Excel XML工作簿 ,但是它不像公认的解决方案那么简单。

Go to this article on LINQtoCSV on Code Project . 在Code Project上转到LINQtoCSV上的这篇文章 Then open the source code in VS and comment out line 201 in FieldMapper.cs to fix a bug that mangles the column ordering: 然后在VS中打开源代码,并在FieldMapper.cs中注释掉第201行,以修复影响列顺序的错误:

//Array.Sort(m_IndexToInfo);

Recompile and you're good to go. 重新编译就可以了。

(I found that from the comments of the article) (我从文章评论中发现)

Then to use: 然后使用:

CsvFileDescription outputFileDescription = new CsvFileDescription
{
    SeparatorChar = '\t', // tab delimited
    FirstLineHasColumnNames = false // no column names in first record
};

CsvContext cc = new CsvContext();

cc.Write(
    YOUR_IQUERYABLE_RESULT_HERE,
    "filename.csv",
    outputFileDescription);

I made a simplified IQueryable <T >.WriteToFile(path) extension method but I don't have it on this machine. 我做了一个简化的IQueryable <T > .WriteToFile(path)扩展方法,但是我在这台机器上没有它。

这个gridview hack是我找到的最简单的解决方案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM