Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

With asp.net, how do I cause a browser to open a tab delimited txt file in Excel?

Tags:

c#

asp.net

We have a tab delimited file that we are making available for download. The file extension is txt, but the users want it to open automatically in Excel. The previous developer had used the following code:

private void DownloadLinkButtonCommandEventHandler(object sender, CommandEventArgs e)
{
    Response.ContentType = "Application/x-msexcel";
    var filePath = (string)e.CommandArgument;
    Response.AppendHeader("content-disposition",
                          "attachment; filename=" + filePath);
    Response.WriteFile(filePath);
    Response.End();
}

The ContentType is being set to Excel, but that doesn't seem to have any effect. I am guessing the txt file extension is causing it to be picked up by notepad or the like instead. I have tried just renaming it to a xls extension, which works but Excel complains that I am trying to trick it or it might be a corrupted file. Any easy win on this? Maybe I should just convert it to an Excel file.

like image 807
Andrew Dunaway Avatar asked Jan 29 '26 16:01

Andrew Dunaway


2 Answers

I would open the file, read the contents into a data structure, and then use any Excel component to spit it back out in Excel format (currently I'm a fan of NPOI).

like image 57
Mike Cole Avatar answered Jan 31 '26 04:01

Mike Cole


You can't rely on mime types (the ContentType). IE has a tendency to ignore the content types specified in the response stream and open up the default application for the downloded file extension.

Would it be easier to convert the file to a CSV which could be as easy as replacing \t with ,?

like image 37
Matthew Abbott Avatar answered Jan 31 '26 06:01

Matthew Abbott