浏览器无法显示Word、excel文件

本文关键字:excel 文件 Word 显示 浏览器 | 更新日期: 2023-09-27 18:10:51

下面的代码在我的。cs文件中。

protected void btnView_Click(对象发送者,EventArgs e){

    string strurl = "ViewFile.ashx?Name=Img/FT.pdf";//Welcome.docx";
    string StrPop = "window.open('"+strurl+"', '_newtab')";
    ScriptManager.RegisterClientScriptBlock(sender as Control, this.GetType(), "OpenWindow", StrPop, true);
}

ViewFile。ashx代码。

public void ProcessRequest (HttpContext){

bool freeDownload = true;

    string supportingFile = context.Request.QueryString["Name"].ToString();
    string strpath = HttpContext.Current.Server.MapPath(supportingFile);
    string strname = Path.GetFileName(strpath);
    string strextension = Path.GetExtension(strpath);
    string strtype = "";
    if (strextension != null)
    {
        switch (strextension.ToLower())
        {
            case ".htm":
            case ".html":
                strtype = "text/HTML";
                break;
            case ".txt":
                strtype = "text/plain";
                break;
            case ".doc":
                strtype = "application/msword";
                break;
            case ".rtf":
                strtype = "application/msword";
                break;
            case ".docx":
                strtype ="application/vnd.openxmlformats-officedocument.wordprocessingml.document" ; //"application/msword";
                break;
            case ".xls":
                strtype = "application/vnd.ms-excel";
                break;
            case ".xlsx":
                strtype = "application/vnd.ms-excel";
                break;
            case ".pdf":
                strtype = "Application/pdf";
                break;
        }
    }
    if (freeDownload)
    {
       // context.Response.AppendHeader("content-disposition", "inline: filename='"" + strname + "'"");
    }
    if (strtype != null)
    {
        FileInfo file = new FileInfo(strpath);
        context.Response.ContentType = strtype;
        context.Response.AddHeader("Content-Disposition", "inline; filename='"" + file.Name + "'"");
        context.Response.AddHeader("Content-Length", file.Length.ToString());
        context.Response.TransmitFile(file.FullName);
        context.Response.WriteFile(strpath);
        context.Response.Flush();
        context.Response.End();
    }
}

有谁能帮帮我吗?当我点击查看按钮时,如果是PDF文件,则显示在浏览器中。但如果是。docx,doc,。xlsx,…直接下载。我如何在浏览器中显示这些文件?

浏览器无法显示Word、excel文件

你可以在按钮上点击创建一个FolderBrowserDialog,给它过滤器到相关的扩展,然后显示给用户,像这样:

FolderBrowserDialog browseDialog;
browseDialog.Filter=" Wordfile (*.dotm; *.dot; *.docx; *.dotx; *.doc; *.docm; *.rtf; *.txt)|*.dotm; *.dot; *.docx; *.dotx; *.doc; *.docm; *.rtf; *.txt";  
if (browseDialog.ShowDialog() == DialogResult.OK)
    {
       MessageBox.Show( System.IO.Path.GetFullPath(browseDialog.FileName));
    }