首先是预览图片,这个功能很好实现,无非就是创建一个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. HearthBuddy中_settings.txt的更详细参数解释

    https://tieba.baidu.com/p/5275382967 默认的配置不是很合理,花了点时间读了下silverfish(也就是兄弟用的AI)的代码后也尝试修改了些参数,有没有效果仁者见仁 ...

  2. 树及其衍生算法(Trees and tree algorithms)

    1,二叉树(Binary tree) 二叉树:每一个节点最多两个子节点,如下图所示: 相关概念:节点Node,路径path,根节点root,边edge,子节点 children,父节点parent,兄 ...

  3. git send-email时报错:Client host rejected: cannot find your hostname 如何处理?

    1. 先找出ip对应的域名 dig +short -x <your ip> 2. 如果第1步没有输出,那么需要将hostname与ip绑定,如:hostname为jello,那么是往/et ...

  4. 使用Selenium时解决方案: Exception: Failed to find firefox binary. You can set it by specifying the ······

    问题描述: Firefox在自动升级之后,在使用selenium的时候出现了如下错误: Exception: Failed to find firefox binary. You can set it ...

  5. 小D课堂 - 新版本微服务springcloud+Docker教程_6-02 springcloud网关组件zuul

    笔记 2.SpringCloud的网关组件zuul基本使用     简介:讲解zuul网关基本使用 1.加入依赖 2.启动类加入注解 @EnableZuulProxy         默认集成断路器 ...

  6. Docker监控:最佳实践以及cAdvisor和Prometheus监控工具的对比

    在DockerCon EU 2015上,Brian Christner阐述了“Docker监控”的概况,分享了这方面的最佳实践和Docker stats API的指南,并对比了三个流行的监控方案:cA ...

  7. jack反序列化自定义字段绑定,报错:can only instantiate non-static inner class by using default, no-argument constructor

    package com.xxx; import com.fasterxml.jackson.annotation.JsonProperty; import lombok.Data; import lo ...

  8. iOS创建带删除线和价钱符号的Label

    效果显示如下: 只需要子类化Label,重写DrawRect()方法即可: #import "MyLabel.h" @implementation MyLabel - (insta ...

  9. 【转载】oracle中decode函数用法

    1.DECODE的语法:DECODE(value,if1,then1,if2,then2,if3,then3,...,else).表示假设value 等于if1时,DECODE函数的结果返回then1 ...

  10. Django之logging配置

    1. settings.py文件 做开发离不开必定离不开日志, 以下是我在工作中写Django项目常用的logging配置. # 日志配置 BASE_LOG_DIR = os.path.join(BA ...