当前位置: 移动技术网 > IT编程>开发语言>.net > Asp.net实现直接在浏览器预览Word、Excel、PDF、Txt文件(附源码)

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

2017年12月12日  | 移动技术网IT编程  | 我要评论

kb2345886,郭依伦雅,问道鬼宠诱饵

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

  预览效果

1、word

2、excel 

3、pdf

4、txt

未解决的问题

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

5.:

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

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网