Word Document.Save在从Ruby或VBS通过OLE调用时忽略编码

我有一个脚本,VBS或Ruby,它将Word文档保存为“过滤的HTML”,但忽略了编码参数。 HTML文件始终在Windows-1252中编码。 我在Windows 7 SP1上使用Word 2007 SP3。

Ruby示例:

require 'win32ole' word = WIN32OLE.new('Word.Application') word.visible = false word_document = word.documents.open('C:\whatever.doc') word_document.saveas({'FileName' => 'C:\whatever.html', 'FileFormat' => 10, 'Encoding' => 65001}) word_document.close() word.quit 

VBS示例:

 Option Explicit Dim MyWord Dim MyDoc Set MyWord = CreateObject("Word.Application") MyWord.Visible = False Set MyDoc = MyWord.Documents.Open("C:\whatever.doc") MyDoc.SaveAs "C:\whatever2.html", 10, , , , , , , , , , 65001 MyDoc.Close MyWord.Quit Set MyDoc = Nothing Set MyWord = Nothing 

文档:

Document.SaveAs: http : //msdn.microsoft.com/en-us/library/bb221597.aspx

msoEncoding值: http : //msdn.microsoft.com/en-us/library/office/aa432511( v = office.12) .aspx

任何建议,如何使Word以UTF-8保存HTML文件?

据我所知,Word无法做到这一点。

但是,您可以在Ruby脚本的末尾添加以下行

 text_as_utf8 = File.read('C:\whatever.html').encode('UTF-8') File.open('C:\whatever.html','wb') {|f| f.print text_as_utf8} 

如果您有旧版本的Ruby,则可能需要使用Iconv 。 如果您在'C:\whatever.html'有特殊字符,则需要查看无效/未定义的替换选项。

您还可能希望更新HTML meta标记中的字符集:

 text_as_utf8.gsub!('charset=windows-1252', 'charset=UTF-8') 

在写入文件之前。

我的解决方案是使用与用于保存它的Word相同的字符集打开HTML文件。 我还添加了一个白名单filter(Sanitize)来清理HTML。 使用Nokogiri进行进一步清洁,Sanitize也依赖于此。

 require 'sanitize' # ... add some code converting a Word file to HTML. # Post export cleanup. html_file = File.open(html_file_name, "r:windows-1252:utf-8") html = '' + html_file.read() html_document = Nokogiri::HTML::Document.parse(html) Sanitize.new(Sanitize::Config::RESTRICTED).clean_node!(html_document) html_document.css('html').first['lang'] = 'en-US' html_document.css('meta[name="Generator"]').first.remove() # ... add more cleaning up of Words HTML noise. sanitized_html = html_document.to_html({:encoding => 'utf-8', :indent => 0}) # writing output to (new) file sanitized_html_file_name = word_file_name.sub(/(.*)\..*$/, '\1.html') File.open(sanitized_html_file_name, 'w:UTF-8') do |f| f.write sanitized_html end 

HTML Sanitizer: https : //github.com/rgrove/sanitize/

HTML解析器和修饰符: http : //nokogiri.org/

在Word 2010中有一种新方法SaveAs2: http : //msdn.microsoft.com/en-us/library/ff836084 (v = office.14) .aspx

我没有测试过SaveAs2,因为我没有Word 2010。

嗨Bo Frederiksen和kardeiz,

我今天在“Word 2003(11.8411.8202)SP3”版本中遇到了“Word Document.SaveAs忽略编码”的问题。

幸运的是,我设法让msoEncodingUTF8(即65001)在VBA代码中工作。 但是,我必须先更改Word文档的设置。 步骤是:

1)从Word的“工具”菜单中,选择“选项”。

2)然后单击“常规”。

3)按“Web选项”按钮。

4)在弹出的“Web选项”对话框中,单击“编码”。

5)你可以找到一个combobox,现在你可以改变编码,例如,从’GB2312’到’Unicode(UTF-8)’。

6)保存更改并尝试重新运行VBA代码。

我希望我的回答可以帮到你。 以下是我的代码。

 Public Sub convert2html() With ActiveDocument.WebOptions .Encoding = msoEncodingUTF8 End With ActiveDocument.SaveAs FileName:=ActiveDocument.Path & "\" & "file_name.html", FileFormat:=wdFormatFilteredHTML, Encoding:=msoEncodingUTF8 End Sub 
Interesting Posts