开发者

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

We have a tab delimited file that we are making available for download. The file e开发者_运维百科xtension 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 want it to open in-place, then the disposition should be "inline", not "attachment".

IE in particular is fussy about the end of the filename; iirc I've had success simply with ?s=.xls - i.e. It only looked (or looked) at the end of the URL; not the content type.

It isn't clear in the example, but you should also ensure nothing else unexpected are in the stream. In particular you mat need to clear any headers that have already been written. Use something like fiddler to check what actually goes down the wire.


Best bet is to get around the excel warnings is to write a native excel file back to the browser.

http://epplus.codeplex.com/

IE sometimes ignores the mimetype; Firefox will ignore the extension if the mimetype is sent.


You used to be able to do this just fine, but newer versions of office don't like it when you try to fool them as you've already discovered. Excel can open tab-delimited .txt files just fine but it sounds like you want it to open directly from the broswer. You could try looking at the XML Spreadsheet format which is supported by Excel. But there your extension has to be .xmlss

Otherwise you'll have to use a third party library to generate an excel document on the server like others have said. Or switch to a different format like csv if possible

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜