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.
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).
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 ,?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With