【发布时间】:2015-08-21 14:02:05
【问题描述】:
我使用此代码(在某处找到)将 csv 转换为 xls。当没有民族字符时,它可以完美运行。 当我尝试使用编码 ISO 2859-2 转换 csv 文件时,我遇到了一些文本错误。知道如何处理这个脚本中的这个字符集吗?
### Set input and output path
$inputCSV = "C:\tmp\test.CSV"
$outputXLSX = "C:\tmp\test.xls"
### Create a new Excel Workbook with one empty sheet which name is the file
$excel = New-Object -ComObject excel.application
$workbook = $excel.Workbooks.Add(1)
$worksheet = $workbook.worksheets.Item(1)
$worksheet.name = "$((GCI $inputCSV).basename)"
### Build the QueryTables.Add command
### QueryTables does the same as when clicking "Data » From Text" in Excel
$TxtConnector = ("TEXT;" + $inputCSV)
$Connector = $worksheet.QueryTables.add($TxtConnector,$worksheet.Range("A1"))
$query = $worksheet.QueryTables.item($Connector.name)
### Set the delimiter ( , or ; ) according to your regional settings
$query.TextFileOtherDelimiter = $Excel.Application.International(5)
### Set the format to delimited and text for every column
### A trick to create an array of 2s is used with the preceding comma
### this options don't seems necessary
$query.TextFileParseType = 1
$query.TextFileColumnDataTypes = ,2 * $worksheet.Cells.Columns.Count
### change decimal separator as "." (can be ",")
$query.TextFileDecimalSeparator = "."
$query.AdjustColumnWidth = 1
### Execute & delete the import query
# using my_output avoid having an outuput that display true
$my_output = $query.Refresh()
$query.Delete()
### Save & close the Workbook as XLS.
$Workbook.SaveAs($outputXLSX,56)
$excel.Quit()
【问题讨论】:
-
能否提供错误信息。
-
我建议converting the CSV file to UTF-8。如果生成的 Unicode 也会被破坏,则问题与 Excel 无关(可能是输入文件编码被破坏)。
-
这不是错误,这些只是在没有正确登录字符集时使用的随机字符,默认情况下在 excel 中使用。我会先尝试将此 csv 转换为 UTF8。
-
转换为 UTF8 没有帮助。当我在 excel 中打开此 CSV 文件时,我看到如下文本中的错误:“Wła¶ciciel”“S±d”。要在 excel 中正确查看文本,我必须将编码设置为 ISO 8859-2 的文本导入。如何在这个 powershell 脚本中做到这一点?
标签: excel powershell csv encoding