tags:

views:

907

answers:

2

I'm generating a report via Linq to SQL and displaying it on the website.

I need to save the report in MS Excel (or .csv) and email it to user.

Any ideas on how to save it as Excel or .csv ?

.NET 3.5 / C#

EDIT:

the Gridview hack works perfect. 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.

<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.

+1  A: 

This gridview hack is the simplest solution I've found.

Chris Pebble
That way works great for a small result set but for larger ones, LINQtoCSV is definitely a better solution.
ifwdev
+2  A: 

Go to this article on LINQtoCSV on Code Project. Then open the source code in VS and comment out line 201 in FieldMapper.cs to fix a bug that mangles the column ordering:

//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.

ifwdev