C#在线预览文档(word,excel,pdf,txt,png)
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
C#在线预览⽂档(word,excel,pdf,txt,png) C#在线预览⽂档(word,excel,pdf,txt,png)
1、预览⽅式:将word⽂件转换成html⽂件然后预览html⽂件
2、预览word⽂件:需要引⼊Interop.Microsoft.Office.Interop.Word.dll(Com组件)
3、预览Excel⽂件:需要引⼊Interop.Microsoft.Office.Interop.Excel.dll(Com组件,Microsoft Excel 12.0(or other version) Object Library)
4、PDF⽂件直接嵌⼊到浏览器中进⾏查看,⽆需转换(需安装pdf阅读器)
5、⽂本⽂件直接嵌⼊到浏览器进⾏查看,⽆需转换
6、图⽚⽂件直接嵌⼊到浏览器进⾏查看,⽆需转换
Excel预览⽅法
using Microsoft.Office.Interop.Excel;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Web;
///<summary>
/// Summary description for ExcelPreview
///</summary>
public class ExcelPreview
{
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();
eShellExecute = true;
process.StartInfo.FileName = outputFile;
process.Start();
}
}
Pdf类
using Microsoft.Office.Interop.Word;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Web;
///<summary>
/// Summary description for WordPreview
///</summary>
public class PDFPreview
{
public static void Priview(System.Web.UI.Page p, string inFilePath)
{
p.Response.ContentType = "Application/pdf";
string fileName = inFilePath.Substring(stIndexOf('\\') + 1);
p.Response.AddHeader("content-disposition", "filename=" + fileName);
p.Response.WriteFile(inFilePath);
p.Response.End();
}
}
Word预览⽅法
using Microsoft.Office.Interop.Word;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Web;
///<summary>
/// Summary description for WordPreview
///</summary>
public class WordPreview
{
public static void Priview(System.Web.UI.Page p, string inFilePath, string outDirPath = "")
{
object missingType = Type.Missing;
object readOnly = true;
object isVisible = false;
object documentFormat = 8;
string randomName = DateTime.Now.Ticks.ToString();
object htmlFilePath = outDirPath + randomName + ".htm";
string directoryPath = outDirPath + randomName + ".files";
object filePath = inFilePath;
//Open the word document in background
ApplicationClass applicationclass = new ApplicationClass();
applicationclass.Documents.Open(ref filePath,
ref readOnly,
ref missingType, ref missingType, ref missingType,
ref missingType, ref missingType, ref missingType,
ref missingType, ref missingType, ref isVisible,
ref missingType, ref missingType, ref missingType,
ref missingType, ref missingType);
applicationclass.Visible = false;
Document document = applicationclass.ActiveDocument;
//Save the word document as HTML file
document.SaveAs(ref htmlFilePath, ref documentFormat, ref missingType,
ref missingType, ref missingType, ref missingType,
ref missingType, ref missingType, ref missingType,
ref missingType, ref missingType, ref missingType,
ref missingType, ref missingType, ref missingType,
ref missingType);
//Close the word document
document.Close(ref missingType, ref missingType, ref missingType);
#region Read the Html File as Byte Array and Display it on browser
//byte[] bytes;
//using (FileStream fs = new FileStream(htmlFilePath.ToString(), FileMode.Open, FileAccess.Read)) //{
// BinaryReader reader = new BinaryReader(fs);
// bytes = reader.ReadBytes((int)fs.Length);
// fs.Close();
//}
//p.Response.BinaryWrite(bytes);
//p.Response.Flush();
//p.Response.End();
#endregion
Process process = new Process();
eShellExecute = true;
process.StartInfo.FileName = htmlFilePath.ToString();
process.Start();
#region Delete the Html File and Diretory 删除⽣成的⽂件
//File.Delete(htmlFilePath.ToString());
//foreach (string file in Directory.GetFiles(directoryPath))
//{
// File.Delete(file);
//}
//Directory.Delete(directoryPath);
#endregion
}
}
⽂本预览⽅法
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
///<summary>
/// Summary description for TextFilePreview
///</summary>
public class TextFilePreview
{
public static void Preview(System.Web.UI.Page p, string inFilePath)
{
string fileName = inFilePath.Substring(stIndexOf('\\') + 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();
}
}
图⽚预览⽅法
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
///<summary>
/// Summary description for TextFilePreview
///</summary>
public class TextFilePreview
{
public static void Preview(System.Web.UI.Page p, string inFilePath)
{
string fileName = inFilePath.Substring(stIndexOf('\\') + 1);
p.Response.ContentType = "images/*";
p.Response.ContentEncoding = System.Text.Encoding.UTF8;
p.Response.AddHeader("content-disposition", "filename=" + fileName);
p.Response.WriteFile(inFilePath);
p.Response.End();
}
}
以上的pdf,txt,图⽚这个三种⽅式在MVC下不可⽤,在aspx界⾯可⽤。
研究后进⾏了更改
以上是转成html进⾏预览,预览效果不是太好。
以下是转成pdf预览代码
1新建windows应⽤程序项⽬
2
3添加以下com组件的引⽤
4
5 Microsoft Word 12.0 Object Library
6
7 Microsoft PowerPoint 12.0 Object Library
8
9 Microsoft Excel 12.0 Object Library
10
11
12
13 ------------------------------------------------------
14
15using Word = Microsoft.Office.Interop.Word; using Excel = Microsoft.Office.Interop.Excel; using PowerPoint = Microsoft.Office.Interop.PowerPoint;
16
17using Microsoft.Office.Core;
18
19
20
21我们可以使⽤⼀个枚举类型来决定⽣成⽂件的类型
22
23 Word.WdExportFormat wd = Microsoft.Office.Interop.Word.WdExportFormat.wdExportFormatPDF;
24
25 Excel.XlFixedFormatType excelType = Microsoft.Office.Interop.Excel.XlFixedFormatType.xlTypePDF; PowerPoint.PpSaveAsFileType ppType = Microsoft.Office.Interop.PowerPoint.PpSaveAsFileType.ppSaveAsPDF; 26
27
28//将word⽂档转换成PDF格式
29private bool Convert(string sourcePath, string targetPath, Word.WdExportFormat exportFormat)
30 {
31bool result;
32object paramMissing = Type.Missing;
33 Word.ApplicationClass wordApplication = new Word.ApplicationClass();
34 Word.Document wordDocument = null;
35try
36 {
37object paramSourceDocPath = sourcePath;
38string paramExportFilePath = targetPath;
39
40 Word.WdExportFormat paramExportFormat = exportFormat;
41bool paramOpenAfterExport = false;
42 Word.WdExportOptimizeFor paramExportOptimizeFor =
43 Word.WdExportOptimizeFor.wdExportOptimizeForPrint;
44 Word.WdExportRange paramExportRange = Word.WdExportRange.wdExportAllDocument;
45int paramStartPage = 0;
46int paramEndPage = 0;
47 Word.WdExportItem paramExportItem = Word.WdExportItem.wdExportDocumentContent;
48bool paramIncludeDocProps = true;
49bool paramKeepIRM = true;
50 Word.WdExportCreateBookmarks paramCreateBookmarks =
51 Word.WdExportCreateBookmarks.wdExportCreateWordBookmarks;
52bool paramDocStructureTags = true;
53bool paramBitmapMissingFonts = true;
54bool paramUseISO19005_1 = false;
55
56 wordDocument = wordApplication.Documents.Open(
57ref paramSourceDocPath, ref paramMissing, ref paramMissing,
58ref paramMissing, ref paramMissing, ref paramMissing,
59ref paramMissing, ref paramMissing, ref paramMissing,
60ref paramMissing, ref paramMissing, ref paramMissing,
61ref paramMissing, ref paramMissing, ref paramMissing,
62ref paramMissing);
63
64if (wordDocument != null)
65 wordDocument.ExportAsFixedFormat(paramExportFilePath,
66 paramExportFormat, paramOpenAfterExport,
67 paramExportOptimizeFor, paramExportRange, paramStartPage,
68 paramEndPage, paramExportItem, paramIncludeDocProps,
69 paramKeepIRM, paramCreateBookmarks, paramDocStructureTags,
70 paramBitmapMissingFonts, paramUseISO19005_1,
71ref paramMissing);
72 result = true;
73 }
74finally
75 {
76if (wordDocument != null)
77 {
78 wordDocument.Close(ref paramMissing, ref paramMissing, ref paramMissing);
79 wordDocument = null;
80 }
81if (wordApplication != null)
82 {
83 wordApplication.Quit(ref paramMissing, ref paramMissing, ref paramMissing);
84 wordApplication = null;
85 }
86 GC.Collect();
87 GC.WaitForPendingFinalizers();
88 GC.Collect();
89 GC.WaitForPendingFinalizers();
90 }
91return result;
92 }
93
94//将excel⽂档转换成PDF格式
95private bool Convert(string sourcePath, string targetPath, XlFixedFormatType targetType)
96 {
97bool result;
98object missing = Type.Missing;
99 Excel.ApplicationClass application = null;
100 Workbook workBook = null;
101try
102 {
103 application = new Excel.ApplicationClass();
104object target = targetPath;
105object type = targetType;
106 workBook = application.Workbooks.Open(sourcePath, missing, missing, missing, missing, missing,
107 missing, missing, missing, missing, missing, missing, missing, missing, missing);
108
109 workBook.ExportAsFixedFormat(targetType, target, XlFixedFormatQuality.xlQualityStandard, true, false, missing, missing, missing, missing); 110 result = true;
111 }
112catch
113 {
114 result = false;
115 }
116finally
117 {
118if (workBook != null)
119 {
120 workBook.Close(true, missing, missing);
121 workBook = null;
122 }
123if (application != null)
124 {
125 application.Quit();
126 application = null;
127 }
128 GC.Collect();
129 GC.WaitForPendingFinalizers();
130 GC.Collect();
131 GC.WaitForPendingFinalizers();
132 }
133return result;
134 }
135
136//将ppt⽂档转换成PDF格式
137private bool Convert(string sourcePath, string targetPath, PpSaveAsFileType targetFileType)
138 {
139bool result;
140object missing = Type.Missing;
141 PowerPoint.ApplicationClass application = null;
142 Presentation persentation = null;
143try
144 {
145 application = new PowerPoint.ApplicationClass();
146 persentation = application.Presentations.Open(sourcePath, MsoTriState.msoTrue, MsoTriState.msoFalse, MsoTriState.msoFalse);
147 persentation.SaveAs(targetPath, targetFileType, Microsoft.Office.Core.MsoTriState.msoTrue);
148
149 result = true;
150 }
151catch
152 {
153 result = false;
154 }
155finally
156 {
157if (persentation != null)
158 {
159 persentation.Close();
160 persentation = null;
161 }
162if (application != null)
163 {
164 application.Quit();
165 application = null;
166 }
167 GC.Collect();
168 GC.WaitForPendingFinalizers();
169 GC.Collect();
170 GC.WaitForPendingFinalizers();
171 }
172return result;
173 }
cshtml代码:
$.get("/Home/Index",{url:a,rnd:new Date()},function(data)
{
if(data.status=1)
{
Window.Open(data.url);//在新窗⼝中打开预览⽂档
}
});
Controller的⽅法
1 Public JsonResult PreView()
2 {
3string url=Request["url"];//url 格式"/doc/123456.pdf"
4string html=Url.Content(url);
5return Json(new {status=1,url=html},JsonRequestBehavior.AllowGet);
6
7 }
转载请注明出处。
此⽅法预览PDf需要机器上安装pdf阅读器。
有好⽅法可以交流学习。