Asp.net实现直接在浏览器预览Word、Excel、PDF、Txt文件(附源码)

发布时间:2022-04-16 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了Asp.net实现直接在浏览器预览Word、Excel、PDF、Txt文件(附源码)脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。

1.功能说明@H_360_2@

输入文件路径,在浏览器输出文件预览信息,经测试360极速(Chrome)、IE9/10、Firefox通过

2.分类文件及代码说明

DemoFiles 存放可测试文件

Default.aspx  启动页

ExcelPreview.cs  Excel预览类

public static void PRiview(System.Web.UI.Page p, string inFilePath, string outDirPath = "")
 {
 Microsoft.Office.Interop.Excel.Application excel = null;
 Microsoft.Office.Interop.Excel.WorkBook xls = null;
 excel = new Microsoft.Office.Interop.Excel.Application();
 object missing = TyPE.Missing;
 object trueObject = true;
 excel.Visible = false;
 excel.DisplayAlerts = false;
 string randomName = DateTime.Now.Ticks.ToString(); //output fileName
 xls = excel.Workbooks.Open(inFilePath, missing, trueObject, missing,
     missing, missing, missing, missing, missing, missing, missing, missing,
     missing, missing, missing);
 //Save Excel to HtML
 object format = Microsoft.Office.Interop.Excel.XlFileFormat.xlHtml;
 Workbook wscurrent = xls;//(Workbook)wsEnumerator.Current;
 String outputFile = outDirPath + randomName + ".html";
 wsCurrent.SaveAs(outputFile, format, missing, missing, missing,
    missing, XlSaveAsAccessMode.xlNoChange, missing,
    missing, missing, missing, missing);
 excel.QuIT();
 //Open generated Html
 Process process = new Process();
 process.StartInfo.UseShellExecute = true;
 process.StartInfo.FileName = outputFile;
 process.Start();
 } 

4.PDFPreview.cs   PDF预览类

public static void Priview(System.Web.UI.Page p, string inFilePath)
 {
 p.Response.ContentType = "Application/pdf";
 string fileName = inFilePath.Substring(inFilePath.LastIndexOf('\\') + 1);
 p.Response.AddHeader("content-disposition", "filename=" + fileName);
 p.Response.WriteFile(inFilePath);
 p.Response.End();
 }

5.TextFilePreview.cs  文本文件预览类

 public static void Preview(System.Web.UI.Page p, string inFilePath)
 {
 string fileName = inFilePath.Substring(inFilePath.LastIndexOf('\\') + 1);
 p.Response.ContentType = "text/plain";
 p.Response.ContentEncoding = System.Text.Encoding.UTF8; //保持和文件的编码格式一致
 p.Response.AddHeader("content-disposition", "filename=" + fileName);
 p.Response.WriteFile(inFilePath);
 p.Response.End();
 }

6. WordPreview.cs  Word预览类

7.Readme.txt  说明了基本功能及引用Com组件的方法(首先需要安装office),需引入的组件包括

  Microsoft Word 15.0
  Microsoft Excel 15.0

  预览效果

1、Word

2、Excel 

3、Pdf

4、Txt

未解决的问题

Pdf、txt文件只能在当前页显示,并导致后退键无效,请各位帮忙解决此两种文件和doc、xls一样在新的tab中打开

5.源码下载http://xiazai.jb51.net/201612/yuanma/FilePreviewInBrowser_jb51.rar

以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,同时也希望多多支持脚本宝典!

脚本宝典总结

以上是脚本宝典为你收集整理的Asp.net实现直接在浏览器预览Word、Excel、PDF、Txt文件(附源码)全部内容,希望文章能够帮你解决Asp.net实现直接在浏览器预览Word、Excel、PDF、Txt文件(附源码)所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。