首先是预览图片,这个功能很好实现,无非就是创建一个html页面,嵌套一个<img>,为了限制图片类型,可以定义一个允许预览类型数组作为限制:

  /// <summary>
/// 预览图片
/// </summary>
/// <param name="physicalPath"></param>
/// <param name="physicalDicPath"></param>
/// <returns></returns>
public string PreviewPic(string physicalPath, string physicalDicPath)
{
string imageName = Path.GetFileNameWithoutExtension(physicalPath);
string htmlName = imageName + ".html";
if (!File.Exists(physicalDicPath + htmlName))
{
FileStream fs = new FileStream(physicalDicPath + htmlName, FileMode.CreateNew);
StreamWriter sw = new StreamWriter(fs, Encoding.UTF8);
StringBuilder sb = new StringBuilder();
sb.Append(@"<!DOCTYPE html>
<html lang = 'zh-CN'><head>
<meta http - equiv = 'Content-Type' content = 'text/html; charset=UTF-8'>
<meta http - equiv = 'X-UA-Compatible' content = 'IE=edge'>
<meta name = 'viewport' content = 'width=device-width, initial-scale=1'>
<title>图片预览</title>
<style>
.content
{
width:80%;
height:auto;
margin:0 auto;
padding:10px 20px;
}
img{
width:80%;
height:auto;
margin: 10px 10%;
}
</style>
</head>");
sb.Append(@"<body><div class='content'>");
var TruePath = "http://" + HttpContext.Current.Request.Url.Authority + "/" + urlconvertor(physicalPath);
sb.Append(@"<img src='" + TruePath + "'/>");
sb.Append(@"</div>");
sb.Append(@"</body>");
sw.Write(sb.ToString()); //这里是写入的内容
sw.Flush();
sw.Close();
}
var resultRul = "http://" + HttpContext.Current.Request.Url.Authority + "/" + urlconvertor(physicalDicPath + htmlName);
return resultRul;
}

然后就是预览excel文件,这个微软为我们提供了现成的方法,打开nuget管理,安装Microsoft.Office.Interop.Excel;经测试xls和xlsx格式都可以成功解析,然后代码如下:

 /// <summary>
/// 预览Excel
/// </summary>
/// <param name="physicalPath">文件物理路径</param>
/// <param name="physicalDicPath">文件夹物理路径</param>
/// <returns>生成页面链接</returns>
public string PreviewExcel(string physicalPath, string physicalDicPath)
{
string htmlName = Path.GetFileNameWithoutExtension(physicalPath) + ".html";
if (!File.Exists(physicalDicPath + htmlName))
{
Microsoft.Office.Interop.Excel.Application application = null;
Microsoft.Office.Interop.Excel.Workbook workbook = null;
application = new Microsoft.Office.Interop.Excel.Application();
object missing = Type.Missing;
object trueObject = true;
application.Visible = false;
application.DisplayAlerts = false;
workbook = application.Workbooks.Open(physicalPath, 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;
String outputFile = Path.GetDirectoryName(physicalPath) + "\\" + htmlName;
workbook.SaveAs(outputFile, format, missing, missing, missing,
missing, XlSaveAsAccessMode.xlNoChange, missing,
missing, missing, missing, missing);
workbook.Close();
application.Quit();
}
var resultRul = "http://" + HttpContext.Current.Request.Url.Authority + "/" + urlconvertor(physicalDicPath + htmlName);
return resultRul;
}

最后就是word的预览了,word的话有两个常见格式:doc,docx;在测试该方法的时候,打开doc格式的word,每次都会弹出转换格式的弹窗,上网查了一下,原来的

Documents.Open()

方法的第二个参数是:真正显示转换文件对话框,如果该文件不是Microsoft Word格式。所以我们只需要将 ConfirmConversions设置为false即可规避这个问题;代码如下:

  /// <summary>
/// 预览Excel
/// </summary>
/// <param name="type">文件格式</param>
/// <param name="physicalPath">文件物理路径</param>
/// <param name="physicalDicPath">文件夹物理路径</param>
/// <returns>生成页面链接</returns>
public string PreviewWord(string physicalPath, string physicalDicPath)
{
string htmlName = Path.GetFileNameWithoutExtension(physicalPath) + ".html";
if (!File.Exists(physicalDicPath + htmlName))
{
Microsoft.Office.Interop.Word._Application application = null;
Microsoft.Office.Interop.Word._Document doc = null;
application = new Microsoft.Office.Interop.Word.Application();
object missing = Type.Missing;
object trueObject = true;
object falseObject = false;
application.Visible = false;
application.DisplayAlerts = WdAlertLevel.wdAlertsNone;
doc = application.Documents.Open(physicalPath, falseObject, trueObject, missing, missing, missing,
missing, missing, missing, missing, missing, missing, missing, missing, missing, missing);
object format = format = Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatHTML;
String outputFile = Path.GetDirectoryName(physicalPath) + "\\" + htmlName;
doc.SaveAs(outputFile, format, missing, missing, missing,
missing, missing, missing,
missing, missing, missing, missing);
doc.Close();
application.Quit();
}
var resultRul= "http://"+HttpContext.Current.Request.Url.Authority +"/"+ urlconvertor(physicalDicPath + htmlName);
return resultRul;
}

最后是预览text,这个实现思想和预览图片是一样的,读取文档内容,填充到html页面上,代码如下:

         /// <summary>
/// 预览Txt
/// </summary>
/// <param name="physicalPath">文件物理路径</param>
/// <param name="physicalDicPath">文件夹物理路径</param>
/// <returns>生成页面链接</returns>
public string PreviewTxt(string physicalPath, string physicalDicPath)
{
FileStream aFile = new FileStream(physicalPath, FileMode.Open);
//暂时不知道为什么获取的编码方式会导致读取的内容为空
//Encoding codeType = GetType(aFile);
StreamReader sr = new StreamReader(aFile, Encoding.GetEncoding("GB2312"));
var content= sr.ReadToEndAsync().Result.Replace("\r\n","</br>");
string htmlName = Path.GetFileNameWithoutExtension(physicalPath) + ".html";
if (!File.Exists(physicalDicPath + htmlName))
{
FileStream fs = new FileStream(physicalDicPath + htmlName, FileMode.CreateNew);
StreamWriter sw = new StreamWriter(fs,Encoding.UTF8);
StringBuilder sb = new StringBuilder();
sb.Append(@"<!DOCTYPE html>
<html lang = 'zh-CN'><head>
<meta http - equiv = 'Content-Type' content = 'text/html; charset=UTF-8'>
<meta http - equiv = 'X-UA-Compatible' content = 'IE=edge'>
<meta name = 'viewport' content = 'width=device-width, initial-scale=1'>
<title>文本预览</title>
<style>
.content
{
width:60%;
height:auto;
margin:0 auto;
border:1px solid #333;
padding:10px 20px;
}
</style>
</head>");
sb.Append(@"<body><div class='content'>");
sb.Append(@"<p>");
sb.Append(content);
sb.Append(@"</p></div>");
sb.Append(@"</body>");
sw.Write(sb.ToString()); //这里是写入的内容
sw.Flush();
sw.Close();
}
sr.Close();
var resultRul = "http://" + HttpContext.Current.Request.Url.Authority + "/" + urlconvertor(physicalDicPath + htmlName);
return resultRul;
}

c# word excel text转html的方法的更多相关文章

  1. 转换成CSV文件、Word、Excel、PDF等的方法--读取CSV文件的方法

    1. 转换成CSV文件: http://www.dotnetgallery.com/lab/resource93-Export-to-CSV-file-from-Data-Table-in-Aspne ...

  2. 共享文件word / excel /ppt 被用戶自己锁定无法编辑-解決方法

    共享文件word / excel /ppt 被用戶自己鎖定無法編輯,但用戶嘗試過關閉所有文件和重啓過系統,依然無法編輯. 搜到解決方法: Just in case someone looking fo ...

  3. 【MVC】 非常简单的页面导出 WORD, EXCEL方法

    [MVC] 页面导出 WORD, EXCEL 前端 js function output() { var para = new Object(); para.html = getHtml(" ...

  4. Office word excel电子表格在线编辑的实现方法

    Office xp之后的版本支持通过webdav协议(http的扩展)直接编辑服务器上的文件. IIS(6.0)支持webdav,这在IIS管理器的web服务扩展中可以看到.利用IIS作为webdav ...

  5. Word,Excel,pdf,txt等文件上传并提取内容

    近期项目需求:1.要用到各种文件上传,下载. 2.并对文件进行搜索. 3.仅仅要文件里包括有搜索的内容,所有显示出来. 今天正好有时间整理一下,方便以后阅读,及对须要用到的朋友提供微薄之力.首先在实现 ...

  6. Java通过openOffice实现word,excel,ppt转成pdf实现在线预览

    Java通过openOffice实现word,excel,ppt转成pdf实现在线预览 一.OpenOffice 1.1 下载地址 1.2 JodConverter 1.3 新建实体类PDFDemo ...

  7. PDF/WORD/EXCEL/PPT 文档在线阅读

    查资料看了2种解决方法: 1.通过办公软件dll转换,用flans去看 2.通过Aspose转换成pdf格式,在用js前台读pdf(我用的pdf.js) 今天我解决的就是WORD/EXCEL/PPT ...

  8. ASP.NET Word/Excel 权限问题

    在部署Word/Excel到服务器的时候,经常会碰到权限问题.例如;   Retrieving the COM class factory for component with CLSID {0002 ...

  9. 读取Excel文件的两种方法

    第一种方法:传统方法,采用OleDB读取EXCEL文件, 优点:写法简单,缺点:服务器必须安有此组件才能用,不推荐使用 private DataSet GetConnect_DataSet2(stri ...

随机推荐

  1. TIZ_c 第0周总结(2019/10/15-2019/10/22)工欲善其事必先利其器

    TIZ_c 第0周总结(2019/10/15-2019/10/22)工欲善其事必先利其器 任务清单 给自己取一个酷酷的id,并选择1-2个喜欢的方向.(只是初步选择,后期可更改) 改下群名片.例如yo ...

  2. 在js中创建命名空间的几种写法

    在JavaScript中全局变量经常会引起命名冲突,甚至有时侯重写变量也不是按照你想像中的顺序来的,可以看看下面的例子:   var sayHello = function() { return 'H ...

  3. ArcGIS Python根据的点坐标,创建点要素

    import arcpy # A list of coordinate pairs # pointList = [[1,2],[3,5],[7,3]] # Create an empty Point ...

  4. fastcgi代理

    一.fastcgi代理 1.示意图 2.fastcgi 代理配置语法 a.设置PHP服务代理地址 Syntax: fastcgi_pass address; Default: — Context: l ...

  5. 解决Sublime Text3中文显示乱码问题

    一.安装包管理器 使用Ctrl+~快捷键或者通过View->Show Console菜单打开命令行,粘贴如下代码 import urllib.request,os; pf = 'Package ...

  6. Oracle 中的进制转换

    Oracle 中的进制转换 */--> Oracle 中的进制转换 Table of Contents 1. 进制名 2. 10进制与16进制互相转换 2.1. 10进制转换为16进制 2.2. ...

  7. hibernate关联映射之多对多

    package loaderman.c_many2many; import java.util.HashSet; import java.util.Set; /** * 开发人员 * * */ pub ...

  8. flutter 常用plugins

    搜索plugins flutter plugins搜索地址 谷歌官方plugins https://pub.dev/packages?q=http 到这个链接里面去搜索 https://github. ...

  9. jmeter之吞吐量控制器

    比如说有一种场景是,10个并发里,有2个事操作业务A,有8个是操作业务B,要模拟这种业务场景,则可以通过吞吐量控制器来模拟 目录 1.用法 2.举例 1.用法 第一种:设置比例控制 选择percent ...

  10. 关于 /proc/sys/net/ipv4/下 文件的详细解释

    关于 /proc/sys/net/ipv4/下 文件的详细解释: 1) /proc/sys/net/ipv4/ip_forward  该文件表示是否打开IP转发.      0,禁止      1,转 ...