简体   繁体   中英

How to view MS office files online in asp.net 4.0, C# web application

Currently, I am working on a file management system which developed in C# & ASP.NET where user can store bulk files. Now I want to view all viewable formats of file (ie image, ms office, pdf etc) open in browser (without downloading in clients local machine). I have already done half of my job ie my application is working fine for all image files and pdf files. But I am facing problems with ms office files (ie .xls , .xlsx , .doc , .docx , .ppt , etc.) formats. I tried some piece of code

    protected void Page_Load(object sender, EventArgs e)
    {
        //Set the appropriate ContentType.
        string FilePath = MapPath("Test/xyz.pdf");
        Response.Buffer = true;
        Response.Clear();
        Response.ClearContent();
        Response.ClearHeaders();
        Response.ContentType = "Application/pdf";
        Response.AddHeader("content-disposition", "inline; filename=\"" + "xyz.pdf" + "\"");
        Response.Write(FilePath);
        Response.End();
    }

This code works fine only for .pdf files but when I changed my content type Response.ContentType for word or excel files Application/msword (for Microsoft Word files) Application/x-msexcel (for Microsoft Excel files) then this code not works. Please guide me what can I do. Should I use any tool like google documents viewer or some thing else.If it is possible only with tool then please suggest me a good tool for this.

Thanks in advance

You could try something like this.

Response.ContentType = application/force-download
Response.AddHeader "content-disposition","attachment; filename=filename.xls

Also for excel I'm seeing some people use: Response.ContentType = "application/vnd.ms-excel" however your MIME for MS Word seems to be good.

Also here is a link to all of the MIME types for MS Office 2007+

如果您正在开发此软件以控制浏览器的使用,即可以指示用户使用的浏览器,则可以尝试使用此组件http://www.ocxt.com/

protected void downloadButton_Click(object sender, EventArgs e)
{
    string fileName = "test.xls";
    string filePath = Server.MapPath("~/test.xls");
    Response.Clear();

    Response.AppendHeader("content-disposition", "attachment; filename=" + fileName);
    Response.ContentType = "application/force-download";
    Response.WriteFile(filePath);
    Response.Flush();
    Response.End();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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