C#.NET实现Word或Excel文件转为HTML文件
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文件的更多相关文章
- 使用 PySide2 开发 Maya 插件系列一:QT Designer 设计GUI, pyside-uic 把 .ui 文件转为 .py 文件
使用 PySide2 开发 Maya 插件系列一:QT Designer 设计GUI, pyside-uic 把 .ui 文件转为 .py 文件 前期准备: 安装 python:https://www ...
- python预课04 列表,元祖,统计值计算示例,py文件转为EXE文件,爬虫初步学习
列表,元组 #list l1 = [1, 2, 3, '高弟弟'] #定义一个列表 #增 l1.append("DSB") #最后增加"DSB"的元素 #删 l ...
- 如何通过WPS 2013 API 将Office(Word、Excel和PPT)文件转PDF文件
1. 描述 PDF 文件是一种便携文件格式,是由Adobe公司所开发的独特的跨平台文件格式.PDF文件以PostScript语言图象模型为基础,无论在哪种打印机上都可保证精确的颜色和准确的打印效果,即 ...
- 将Excel文件转为csv文件的python脚本
#!/usr/bin/env python __author__ = "lrtao2010" ''' Excel文件转csv文件脚本 需要将该脚本直接放到要转换的Excel文件同级 ...
- 将Rmarkdown文件转为pdf文件
knitr包只能够将R markdown文件转为html格式,若想要将其转化为pdf格式,还要安装另一个包 # Install and load package install.packages(&q ...
- Spring-Batch将CSV文件转为XML文件
1 介绍 用Spring Batch实现一个简单的需求,将csv文件转换成xml文件. csv文件如下:record.csv username, user_id, transaction_date, ...
- html 实现动态在线预览word、excel、pdf等文件(方便快捷)
https://blog.csdn.net/superKM/article/details/81013304 太方便了 <iframe src='https://view.officeapps. ...
- 关于python文件转为exe文件
一.简介 py2exe是一个将python脚本转换成windows上的可独立执行的可执行程序(*.exe)的工具,这样,你就可以不用装python而在windows系统上运行这个可执行程序. py2e ...
- Ant将Jmeter的jtl文件转为html文件报“前言中不允许有内容”
ant执行jmeter的脚本的时候提示“Fatal Error! 前言中不允许有内容” 解决办法: 在jmeter的bin目录中找到jmeter.properties: 将文件中#jmeter.sav ...
随机推荐
- Yeoman+Express+Angular在Linux上开发配置方法
$mkdir ExpressWithAngularTest $cd ExpressWithAngularTest choose needed components you'd like to add ...
- 关于Web端即JS端编程
主要的技术是 HTML/JS/CSS/XML Web就是JS/DOM编程. 页面的数据来源: XML, JSON, HTML, Text, 第三方页面或者数据. 不一定都要跟服务器进行交互. JS端 ...
- TP复习
第一课,三步骤 1,.名称 2.路径 3.引用核心文件 4,.公用的可以建立public upload css 等 第二课 uRL四中模式 ~ActionClass.php 一.什么是MVC / ...
- iOS开发——多线程OC篇&多线程详解
多线程详解 前面介绍了多线程的各种方式及其使用,这里补一点关于多线程的概念及相关技巧与使用,相信前面不懂的地方看了这里之后你就对多线程基本上没有什么问题了! 1——首先ios开发多线程中必须了解的概念 ...
- System.setProperty()
/* * 设置指定键对值的系统属性 * setProperty (String prop, String value); * * 參数: * prop - 系统属性的名称. * value ...
- android学习日记13--数据存储之ContentProvide
3.ContentProvider 数据在Android当中是私有的,当然这些数据包括文件数据和数据库数据以及一些其他类型的数据.ContentProvider实现多应用程序间的数据共享类一般利用Co ...
- flume监控之ganglia
对于日志来说,我觉得监控意义不大,因为写的速度一般不会特别快,但是如果是spooldir source,里面一小时放入十几G的数据让flume解析,特别是在结合kafka或者其他框架的话,监控就显得重 ...
- A Simple Problem with Integers 多树状数组分割,区间修改,单点求职。 hdu 4267
A Simple Problem with Integers Time Limit: 5000/1500 MS (Java/Others) Memory Limit: 32768/32768 K ...
- 【阿里云产品公测】OTS使用之简单线上产品实践基于PythonSDK
阿里云用户:morenocjm 实践是检验真理的唯一标准,学习技术需要通过实践过程中的不断尝试,才能够快速掌握要领.OTS是构建在阿里云飞天分布式系统之上的NoSQL数据库服务,提供海量结构化数据的存 ...
- UITabbar的简单操作和实际应用
简易编辑Tabbar //**标签栏控制器的初始化 UITabBarController * tabbarC = [[UITabBarController alloc] init]; //设置tab ...