首先是预览图片,这个功能很好实现,无非就是创建一个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. 爬虫实践——数据存储到Excel中

    在进行爬虫实践时,我已经爬取到了我需要的信息,那么最后一个问题就是如何把我所爬到的数据存储到Excel中去,这是我没有学习过的知识. 如何解决这个问题,我选择先百度查找如何解决这个问题. 百度查到的方 ...

  2. NProgress的使用 及 路由 token 定向的使用

    主要配合路由生命周期使用 实现一个进度条的效果 使用方法: 1. 下载:npm install --save nprogress 使用:NProgress.start();  开始 NProgress ...

  3. ffmpeg编码h264设置规格

    ffmpeg -i demo.ts -profile:v baseline -vcodec h264 -acodec aac -f flv demo.flv

  4. js 时间戳格式化日期格式

    时间戳转换为日期,网上搜了好几个或多或少都有点问题,自己整理了一下,写了个方法 console.log(formatDate(1565280000000)) 输出: 2019-08-09 00:00: ...

  5. LC 638. Shopping Offers

    In LeetCode Store, there are some kinds of items to sell. Each item has a price. However, there are ...

  6. AndroidStudio NDK环境3种搭建方式

    AndroidStudio NDK环境3种搭建方式     转载. https://blog.csdn.net/zhang_jun_ling/article/details/85621427 一.前言 ...

  7. BeanUtils.getProperty性能分析

    接上文Java各种反射性能对比 BeanUtils.getProperty的原理其实以下方法类似,但稍有不同 //代码片段4.1        PropertyDescriptor descripto ...

  8. k8s-高可用多主master配置

    准备主机 centos7镜像 node1: 192.168.0.101 node2: 192.168.0.102 node3: 192.168.0.103 vip: 192.168.0.104 配置s ...

  9. 实时更新Excel文档外部数据源的数据

    实时更新Excel文档外部数据源的数据 单元格区域.Excel 表.数据透视表或数据透视图均可以连接到外部数据源(数据源:用于连接数据库的一组存储的"源"信息.数据源包含数据库服务 ...

  10. 【JVM学习笔记】字节码文件结构实例

    上一篇笔记的内容大部分没有实际动手操作,因此决定完成这个完整的练习并记录下来. 另注,idea环境下有jclasslib插件用于更好的查看类似于javap结果的内容. 源代码如下: package c ...