這個是CodeProject上的一篇文章:Microsoft Interop API to convert the .doc, .docx, .dot, .dotx and .xls,.xlsx, .rtf to HTML。該文介紹了一種通過Microsoft office Interop library轉換word或excel文檔為html的方法,這里轉錄一下,以供更多需要的人參考。
要使用Microsoft office Interop library庫,首先得在電腦上安裝Office,然后添加如下三個com組件的引用:
-
Microsoft Office Excel library.
-
Microsoft Office Word library
-
Microsoft Office object library
作者編寫了兩個類DocToHtml和XlsToHtml用以轉換Word和Excel文檔,
public static IConverter Converter(string fullFilePath, string fileToSave)
{
switch (Path.GetExtension(fullFilePath).ToLower())
{
case ".doc":
case ".docx":
case ".dot":
case ".dotx":
case ".rtf":
return new DocToHtml { FileToSave = fileToSave, FullFilePath = fullFilePath };
case ".xls":
case ".xlsx":
return new XlsToHtml { FileToSave = fileToSave, FullFilePath = fullFilePath };
default:
throw new NotSupportedException();
}
}
使用方法如下:
static void Main(string[] args)
{
var converter = ConverterLocator.Converter(@"r:\1.xlsx", @"r:\1.html");
var html = converter.Convert();
}
原文提供了代碼的下載,使用了一下,覺得有兩個問題:
1. 該代碼轉換后會刪除原始文件,並且也不會保留轉換后的文件,僅僅返回string類型的html。
轉換后刪除原始文件是不對的,並且string類型的html文件有並不能完全代表結果(很多時候還有一些圖片或樣式表之類的附加文件)。因此我把代碼修改了一下,不刪除原始文件和轉換后的文件。
2. 轉換帶圖片的文檔時會報異常
分析了一下,轉換帶圖片的文檔后,會生成一個xxx.files的文件夾用以存放文檔,但是作者的代碼中是xxx_files文件夾(可能是操作系統或office的版本不一樣所致),我這里改成了xxx.files后就不報異常了。
修改后的代碼下載地址如下:點擊下載。
