改变编码的问题

时间:2017-11-22 11:36:45

标签: powershell word-vba

我正在使用PowerShell脚本将docx转换为HTML,并且还要更改HTML的编码,因为默认情况下会将其保存为windows-1252。

我需要这个,因为稍后我发送这个保存为电子邮件正文的HTML也由PowerShell发送。由于我是西班牙语,我需要重音符号和波形符号才能显示(现在显示为?)。

我尝试了所有参数的SaveAs方法,但我无法让它工作。

这是我的剧本:

$MSWord = New-Object -ComObject Word.Application
$MSWord.Documents.Open(“C:\Users\USER\Videos\CAMBIO_TURNO.docx”)
$MSWord.Visible = $false

# Save HTML
$saveFormat = [Enum]::Parse([Microsoft.Office.Interop.Word.WdSaveFormat], “wdFormatHTML”);
$path = “C:\Users\USER\Videos\CAMBIO_TURNO.html”
$MSWord.ActiveDocument.SaveAs([ref]$path, [ref]$saveFormat)

# Close File

$MSWord.ActiveDocument.Close()
$MSWord.Quit()

然后,要将它发送给我,我在PowerShell上使用其他代码:

$OutputEncoding = [System.Text.Encoding]::UTF8

$body = [IO.File]::ReadAllText(“C:\Users\USER\Videos\CAMBIO_TURNO.html”)

Send-MailMessage -To “EMAIL@EMAIL” -From “EMAIL@EMAIL” -Subject “CAMBIO” -Body $body -Encoding $OutputEncoding -BodyAsHtml -Attachments “C:\Users\USER\Videos\CAMBIO_TURNO.xlsx” -Dno onSuccess, onFailure -SmtpServer smtp.gmail.com -Credential EMAIL@EMAIL

第二次更新

(虽然我转到了标记为重复的页面:Word Document.SaveAs ignores encoding, when calling through OLE, from Ruby or VBS但它没有解决我的问题。这个单词配置不起作用)

以下是我使用网络选项以utf-8保存文档后尝试的内容:

#DEFINE outputencoding FOR THE CONSOLE - IT SEEMS THAT IT DOESN'T WORK. I typed ñ and ó and they appear as ?? becasue it doesn't convert the hexadecimal values to the right charset
$OutputEncoding= New-Object -typename System.Text.ASCIIEncoding

# Open word to add input into the signature file
$MSWord = New-Object -ComObject word.application
$MSWord.Documents.Open('C:\Users\USER\Videos\CAMBIO_TURNO.docx')

 # Save HTML
$saveFormat = [Enum]::Parse([Microsoft.Office.Interop.Word.WdSaveFormat], 'wdFormatFilteredHTML');

$path = 'C:\Users\USER\Videos\CAMBIO_TURNO.html'

$default = [Type]::Missing
$MSWord.ActiveDocument.SaveAs2([ref]$path, [ref]$saveFormat, [ref]$default, [ref]$default, [ref]$default, [ref]$default, [ref]$default, [ref]$default, [ref]$default, [ref]$default, [ref]$default, [ref]28591)

# Close File
$MSWord.ActiveDocument.Close()
$MSWord.Quit()

$HTMLw = Get-Content -Path 'C:\Users\USER\Videos\CAMBIO_TURNO.html' -Encoding ASCII -Force
$HTMLw -replace 'charset=windows-1252','charset=ISO-8859-1' | Set-Content -Path 'C:\Users\USER\Videos\CAMBIO_TURNO.html' -Encoding ASCII -Force

1 个答案:

答案 0 :(得分:0)

首先,你应该避免使用印刷引号()。始终在代码中使用直引号(")。

话虽如此,你所面临的问题很可能是传递一个带有符号常量名称的字符串不起作用。要么使用常量的numeric value,要么自己定义一个常量:

New-Variable -Name wdFormatHTML -Value 8 -Option Constant
$MSWord.ActiveDocument.SaveAs($path, $wdFormatHTML)

或者你应该能够解析常量via the Interop API,但我现在手头没有Office安装,所以我无法测试。

保存时,您也没有指定输出文件的所需编码。

New-Variable -Name wdFormatHTML -Value 8 -Option Constant
$default = [Type]::Missing
$MSWord.ActiveDocument.SaveAs($path, $wdFormatHTML, $default, $default, $default, $default, $default, $default, $default, $default, $default, 65001)