1200字范文,内容丰富有趣,写作的好帮手!
1200字范文 > Asp.net实现直接在浏览器预览Word Excel PDF Txt文件(附源码)

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

时间:2023-01-02 18:34:20

相关推荐

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

功能说明输入文件路径,在浏览器输出文件预览信息,经测试360极速(Chrome)、IE9/10、Firefox通过分类文件及代码说明DemoFiles 存放可测试文件Default.aspx 启动页ExcelPreview.cs Excel预览类publicstaticvoidPriview(System.Web.UI.Pagep,stringinFilePath,stringoutDirPath="")

{

Microsoft.Office.Interop.Excel.Applicationexcel=null;

Microsoft.Office.Interop.Excel.Workbookxls=null;

excel=newMicrosoft.Office.Interop.Excel.Application();

objectmissing=Type.Missing;

objecttrueObject=true;

excel.Visible=false;

excel.DisplayAlerts=false;

stringrandomName=DateTime.Now.Ticks.ToString();//outputfileName

xls=excel.Workbooks.Open(inFilePath,missing,trueObject,missing,

missing,missing,missing,missing,missing,missing,missing,missing,

missing,missing,missing);

//SaveExceltoHtml

objectformat=Microsoft.Office.Interop.Excel.XlFileFormat.xlHtml;

WorkbookwsCurrent=xls;//(Workbook)wsEnumerator.Current;

StringoutputFile=outDirPath+randomName+".html";

wsCurrent.SaveAs(outputFile,format,missing,missing,missing,

missing,XlSaveAsAccessMode.xlNoChange,missing,

missing,missing,missing,missing);

excel.Quit();

//OpengeneratedHtml

Processprocess=newProcess();

process.StartInfo.UseShellExecute=true;

process.StartInfo.FileName=outputFile;

process.Start();

} 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();}

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();}

WordPreview.cs Word预览类Readme.txt 说明了基本功能及引用Com组件的方法(首先需要安装office),需引入的组件包括Microsoft Word15.0MicrosoftExcel15.0

预览效果

1、Word

2、Excel

3、Pdf

4、Txt

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

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。