Word文件转html,返回相对路径

 private string GetPathByDocToHTML(string strFile)
{
if (string.IsNullOrEmpty(strFile))
{
return "";//没有文件
} Microsoft.Office.Interop.Word.ApplicationClass word = new Microsoft.Office.Interop.Word.ApplicationClass();
Type wordType = word.GetType();
Microsoft.Office.Interop.Word.Documents docs = word.Documents; // 打开文件
Type docsType = docs.GetType(); object fileName = strFile; Microsoft.Office.Interop.Word.Document doc = (Microsoft.Office.Interop.Word.Document)docsType.InvokeMember("Open",
System.Reflection.BindingFlags.InvokeMethod, null, docs, new Object[] { fileName, true, true }); // 转换格式,另存为html
Type docType = doc.GetType();
//给文件重新起名
string filename = System.DateTime.Now.Year.ToString() + System.DateTime.Now.Month.ToString() + System.DateTime.Now.Day.ToString() +
System.DateTime.Now.Hour.ToString() + System.DateTime.Now.Minute.ToString() + System.DateTime.Now.Second.ToString(); string strFileFolder = "../html/";
DateTime dt = DateTime.Now;
//以yyyymmdd形式生成子文件夹名
string strFileSubFolder = dt.Year.ToString();
strFileSubFolder += (dt.Month < ) ? ("" + dt.Month.ToString()) : dt.Month.ToString();
strFileSubFolder += (dt.Day < ) ? ("" + dt.Day.ToString()) : dt.Day.ToString();
string strFilePath = strFileFolder + strFileSubFolder + "/";
// 判断指定目录下是否存在文件夹,如果不存在,则创建
if (!Directory.Exists(Server.MapPath(strFilePath)))
{
// 创建up文件夹
Directory.CreateDirectory(Server.MapPath(strFilePath));
} //被转换的html文档保存的位置
// HttpContext.Current.Server.MapPath("html" + strFileSubFolder + filename + ".html")
string ConfigPath = Server.MapPath(strFilePath + filename + ".html");
object saveFileName = ConfigPath; /*下面是Microsoft Word 9 Object Library的写法,如果是10,可能写成:
* docType.InvokeMember("SaveAs", System.Reflection.BindingFlags.InvokeMethod,
* null, doc, new object[]{saveFileName, Word.WdSaveFormat.wdFormatFilteredHTML});
* 其它格式:
* wdFormatHTML
* wdFormatDocument
* wdFormatDOSText
* wdFormatDOSTextLineBreaks
* wdFormatEncodedText
* wdFormatRTF
* wdFormatTemplate
* wdFormatText
* wdFormatTextLineBreaks
* wdFormatUnicodeText
*/
docType.InvokeMember("SaveAs", System.Reflection.BindingFlags.InvokeMethod,
null, doc, new object[] { saveFileName, Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatFilteredHTML }); //docType.InvokeMember("SaveAs", System.Reflection.BindingFlags.InvokeMethod,
// null, doc, new object[] { saveFileName, Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatFilteredHTML }); //关闭文档
docType.InvokeMember("Close", System.Reflection.BindingFlags.InvokeMethod,
null, doc, new object[] { null, null, null }); // 退出 Word
wordType.InvokeMember("Quit", System.Reflection.BindingFlags.InvokeMethod, null, word, null);
//转到新生成的页面
//return ("/" + filename + ".html"); //转化HTML页面统一编码格式
TransHTMLEncoding(ConfigPath); return (strFilePath + filename + ".html");
}

Excel文件转HTML,返回相对路径

 private string GetPathByXlsToHTML(string strFile)
{
if (string.IsNullOrEmpty(strFile))
{
return "";//没有文件
} //实例化Excel
Microsoft.Office.Interop.Excel.Application repExcel = new Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel.Workbook workbook = null;
Microsoft.Office.Interop.Excel.Worksheet worksheet = null; //打开文件,n.FullPath是文件路径
workbook = repExcel.Application.Workbooks.Open(strFile, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
worksheet = (Microsoft.Office.Interop.Excel.Worksheet)workbook.Worksheets[]; //给文件重新起名
string filename = System.DateTime.Now.Year.ToString() + System.DateTime.Now.Month.ToString() + System.DateTime.Now.Day.ToString() +
System.DateTime.Now.Hour.ToString() + System.DateTime.Now.Minute.ToString() + System.DateTime.Now.Second.ToString(); string strFileFolder = "../html/";
DateTime dt = DateTime.Now;
//以yyyymmdd形式生成子文件夹名
string strFileSubFolder = dt.Year.ToString();
strFileSubFolder += (dt.Month < ) ? ("" + dt.Month.ToString()) : dt.Month.ToString();
strFileSubFolder += (dt.Day < ) ? ("" + dt.Day.ToString()) : dt.Day.ToString();
string strFilePath = strFileFolder + strFileSubFolder + "/";
// 判断指定目录下是否存在文件夹,如果不存在,则创建
if (!Directory.Exists(Server.MapPath(strFilePath)))
{
// 创建up文件夹
Directory.CreateDirectory(Server.MapPath(strFilePath));
}
string ConfigPath = Server.MapPath(strFilePath + filename + ".html");
object savefilename = (object)ConfigPath; object ofmt = Microsoft.Office.Interop.Excel.XlFileFormat.xlHtml;
//进行另存为操作
workbook.SaveAs(savefilename, ofmt, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
object osave = false;
//逐步关闭所有使用的对象
workbook.Close(osave, Type.Missing, Type.Missing);
repExcel.Quit();
System.Runtime.InteropServices.Marshal.ReleaseComObject(worksheet);
worksheet = null;
//垃圾回收
GC.Collect();
System.Runtime.InteropServices.Marshal.ReleaseComObject(workbook);
workbook = null;
GC.Collect();
System.Runtime.InteropServices.Marshal.ReleaseComObject(repExcel.Application.Workbooks);
GC.Collect();
System.Runtime.InteropServices.Marshal.ReleaseComObject(repExcel);
repExcel = null;
GC.Collect();
//依据时间杀灭进程
System.Diagnostics.Process[] process = System.Diagnostics.Process.GetProcessesByName("EXCEL");
foreach (System.Diagnostics.Process p in process)
{
if (DateTime.Now.Second - p.StartTime.Second > && DateTime.Now.Second - p.StartTime.Second < )
{
p.Kill();
}
} return (strFilePath + filename + ".html");
}

这里可能会遇到一个问题,由于转化为HTML文件的页面编码可能使得浏览器无法正确解读,所以需要转码,转换代码如下:

     private void TransHTMLEncoding(string strFilePath)
{
try
{
System.IO.StreamReader sr = new System.IO.StreamReader(strFilePath, Encoding.GetEncoding());
string html = sr.ReadToEnd();
sr.Close();
html = System.Text.RegularExpressions.Regex.Replace(html, @"<meta[^>]*>", "<meta http-equiv=Content-Type content='text/html; charset=gb2312'>", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
System.IO.StreamWriter sw = new System.IO.StreamWriter(strFilePath, false, Encoding.Default); sw.Write(html);
sw.Close();
}
catch (Exception ex)
{
Page.RegisterStartupScript("alt", "<script>alert('" + ex.Message + "')</script>");
}
}

这样就可以正常在页面上正常显示了

C#.NET实现Word或Excel文件转为HTML文件的更多相关文章

  1. 使用 PySide2 开发 Maya 插件系列一:QT Designer 设计GUI, pyside-uic 把 .ui 文件转为 .py 文件

    使用 PySide2 开发 Maya 插件系列一:QT Designer 设计GUI, pyside-uic 把 .ui 文件转为 .py 文件 前期准备: 安装 python:https://www ...

  2. python预课04 列表,元祖,统计值计算示例,py文件转为EXE文件,爬虫初步学习

    列表,元组 #list l1 = [1, 2, 3, '高弟弟'] #定义一个列表 #增 l1.append("DSB") #最后增加"DSB"的元素 #删 l ...

  3. 如何通过WPS 2013 API 将Office(Word、Excel和PPT)文件转PDF文件

    1. 描述 PDF 文件是一种便携文件格式,是由Adobe公司所开发的独特的跨平台文件格式.PDF文件以PostScript语言图象模型为基础,无论在哪种打印机上都可保证精确的颜色和准确的打印效果,即 ...

  4. 将Excel文件转为csv文件的python脚本

    #!/usr/bin/env python __author__ = "lrtao2010" ''' Excel文件转csv文件脚本 需要将该脚本直接放到要转换的Excel文件同级 ...

  5. 将Rmarkdown文件转为pdf文件

    knitr包只能够将R markdown文件转为html格式,若想要将其转化为pdf格式,还要安装另一个包 # Install and load package install.packages(&q ...

  6. Spring-Batch将CSV文件转为XML文件

    1 介绍 用Spring Batch实现一个简单的需求,将csv文件转换成xml文件. csv文件如下:record.csv username, user_id, transaction_date, ...

  7. html 实现动态在线预览word、excel、pdf等文件(方便快捷)

    https://blog.csdn.net/superKM/article/details/81013304 太方便了 <iframe src='https://view.officeapps. ...

  8. 关于python文件转为exe文件

    一.简介 py2exe是一个将python脚本转换成windows上的可独立执行的可执行程序(*.exe)的工具,这样,你就可以不用装python而在windows系统上运行这个可执行程序. py2e ...

  9. Ant将Jmeter的jtl文件转为html文件报“前言中不允许有内容”

    ant执行jmeter的脚本的时候提示“Fatal Error! 前言中不允许有内容” 解决办法: 在jmeter的bin目录中找到jmeter.properties: 将文件中#jmeter.sav ...

随机推荐

  1. C#缩放和裁剪图片

    在GDI+中,缩放和剪裁可以看作同一个操作,无非就是原始区域的选择不同罢了.空口无凭,先看具体算法可能更好理解. using System; using System.Collections.Gene ...

  2. Skyline TerraExplorer Pro(等ActiveX控件)在Google Chrome浏览器的运行方法

    首先感谢ActiveX for Chrome 网银助手(np-activex)这个项目(https://code.google.com/p/np-activex/),解决了我们困惑很久的问题——在Ch ...

  3. Android——ViewGroup的一个用法实例(转载)

    找了很久,终于找到了. <?xml version="1.0" encoding="UTF-8" ?> <merge xmlns:androi ...

  4. iframe自适应高度的多种方法小结

    转自:http://www.jb51.net/article/15780.htm 不带边框的iframe因为能和网页无缝的结合从而不刷新页面的情况下更新页面的部分数据成为可能,可是 iframe的大小 ...

  5. Ubuntu:Target filesystem doesn&#39;t have /sbin/init (Slax 解决)

    计算机(Ubuntu)因为异常断电或是其它原因,再次启动时.非常不幸的出现: Killed mount: mounting /dev on /root/dev failed: No such file ...

  6. cocos2d-html5的jsb模式下如何在编译时自动将js编译为jsc

    cocos2d-html5是一个用JS来开发游戏的框架,通过javascript Binding的方式可以将游戏编译到手机上.这对前端开发人员来说非常方便,开发效率也比使用c++开发要快的多. jsb ...

  7. error C2440:“类型转换":无法从“void (__thiscall Play1::* )(int *)”转换为“cocos2d::SEL_CallFucN

    转自:http://zhidao.baidu.com/link?url=VfSSkA0xfTVwNKaKh4tqW_sXlcsK-Rb16nEtQw5zaq5_306lnwJN3Kdb-rFp-r4L ...

  8. 项目源码--Android即时通讯IM客户端

    下载源码   技术要点: 1.完整精美客户端UI设计 2.自定义控件的灵活使用 3.UI控件的详细使用 4.即时通讯IM协议的实现 5.完整即时通讯IM客户端实现 6.源码详细的中文注释 …….   ...

  9. Linux scp 使用详解

    一般情况,本地网络跟远程网络进行数据交抱,或者数据迁移,常用的有三种方法,一是ftp,二是wget /fetch 三是,rsync 大型数据迁移用rysync,其次用fetch/wget ,最次是ft ...

  10. Apache的编译安装error: APR not found. Please read the documentation

    提示configure: error: APR not found. Please read the documentation. 经网上查阅资料才知道这是Apache的关联软件 在apr.apach ...