通过OLE调用时,SaveAs忽略来自Ruby或VBS的编码

uujelgoq  于 2023-03-17  发布在  Ruby
关注(0)|答案(3)|浏览(130)

我有一个脚本(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
mso编码值:http://msdn.microsoft.com/en-us/library/office/aa432511(v=office.12).aspx
有什么建议,如何让Word保存的HTML文件在UTF-8?

ujv3wf0j

ujv3wf0j1#

嗨,博·弗雷德里克森和卡戴兹,
我今天在“Word 2003(11.8411.8202)SP3”版本中也遇到了“Word文档。SaveAs忽略编码”的问题。
幸运的是,我设法使msoEncodingUTF 8(即65001)在VBA代码中工作。但是,我必须首先更改Word文档的设置。步骤如下:
1)从Word的“工具”菜单中选择“选项”。
2)然后单击“常规”。
3)按“Web选项”按钮。
4)在弹出的“Web选项”对话框中,单击“编码”。
5)您可以找到一个组合框,现在您可以更改编码,例如,从'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
kmpatx3s

kmpatx3s2#

据我所知,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')

然后再写入文件。

2nc8po8w

2nc8po8w3#

我的解决方案是使用与Word保存时相同的字符集打开HTML文件。我还添加了一个白名单过滤器(Sanitize)来清理HTML。进一步的清理是使用Nokogiri完成的,Sanitize也依赖Nokogiri。

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 = '<!DOCTYPE html>' + html_file.read()
html_document = Nokogiri::HTML::Document.parse(html)
Sanitize.new(Sanitize::Config::RESTRICTED).clean_node!(html_document)
html_document.at_css('html')['lang'] = 'en-US'
html_document.at_css('meta[name="Generator"]').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清理程序: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。

相关问题