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 ...
随机推荐
- [Angular2 Router] Optional Route Query Parameters - The queryParams Directive and the Query Parameters Observable
In this tutorial we are going to learn how to use the Angular 2 router to pass optional query parame ...
- Java Web模块——验证码模块
一.什么是验证码及它的作用 验 证码为全自动区分计算机和人类的图灵测试的缩写,是一种区分用户是计算机的公共全自动程序,这个问题可以由计算机生成并评判,但是必须只有人类才能解答. 可以防止恶意破解密码. ...
- CHECKPOINT
http://blog.csdn.net/chenlvzhou/article/details/41518979
- android studio无法更新之解决方案
当发现android studio有更新时,当然第一时间就想更新,可惜被墙了. 解决方案: 下载wallproxy,百度你懂的 在proxy.ini中最上面,找到ip和port 接着,在android ...
- 代码片段 - Golang 创建 .tar.gz 压缩包
Golang创建 .tar.gz 压缩包 tar 包实现了文件的打包功能,可以将多个文件或目录存储到单一的 .tar 文件中,tar 本身不具有压缩功能,只能打包文件或目录: import " ...
- php 运行客户提交代码(攻击)和运行图片中的代码
1.$a=@strrev(ecalper_gerp);$b=@strrev(edoced_46esab);@$a($b(L3h4L2Ug),$_POST[POST],bxxb); 2.<?php ...
- cocos2dx-lua使用UIListView制作二级折叠菜单
折叠菜单,用过jquery accordion的同学都知道是啥玩艺儿~,图片效果就是介样: cocos2dx不带有此控件,因此我们动手来实现一个. 原理很简单,展开的时候往listview里inser ...
- initrd映像文档的作用和制作
1.http://pan.baidu.com/s/1dDrGeKL 2.http://wenku.baidu.com/link?url=qPa_jfkEZCbERnwMYWLwm9EZJ_ebMRJA ...
- Android——AnimationDrawable 实现动画
Android中的AnimationDrawable可以加载Drawable资源实现帧动画.实现步骤如下: 一.设置动画播放的帧资源 <?xml version="1.0" ...
- Java最重要的21个技术点和知识点之JAVA面向对象
(二)Java最重要的21个技术点和知识点之JAVA面向对象 写这篇文章的目的是想总结一下自己这么多年JAVA培训的一些心得体会,主要是和一些java基础知识点相关的,所以也希望能分享给刚刚入门的J ...