欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2022-06-03 15:09:27
1.功能说明 输入文件路径,在浏览器输出文件预览信息,经测试360极速(chrome)、ie9/10、firefox通过 2.分类文件及代码说明 demofiles...

1.功能说明

输入文件路径,在浏览器输出文件预览信息,经测试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

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

  预览效果

1、word

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

2、excel 

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

3、pdf

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

4、txt

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

未解决的问题

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

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

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