使用PowerShell将带有行定界符的CSV导入Excel

时间:2018-12-28 13:29:22

标签: excel powershell csv

需要PowerShell脚本的帮助,以将列分隔符为|且行分隔符为&(不是回车符)的CSV文件导入Excel。

以下是CSV文件的示例:

row1col1|row1col2|row1col3|row1col4&row2col1|row2col2|row2col3|row2col4&row3col1|row3col2|row3col3|row3col4 etc.

我找到了此脚本,但仅在行定界符为CR(回车)时有效。我应该添加哪些行才能使其与&符号(而不是CR)一起使用。

#Define locations and delimiter
$csv = "file.csv"   #Location of the source file
$xlsx = "file.xlsx" #Desired location of output

$delimiter = "|" #Specify the delimiter used in the file

# Create a new Excel workbook with one empty sheet
$excel = New-Object -ComObject Excel.Application
$workbook = $excel.Workbooks.Add(1)
$worksheet = $workbook.Worksheets.Item(1)

# Build the QueryTables.Add command and reformat the data
$TxtConnector = ("TEXT;" + $csv)

$Connector = $worksheet.QueryTables.Add($TxtConnector, $worksheet.Range("A1"))

$query = $worksheet.QueryTables.Item($Connector.Name)
$query.TextFileOtherDelimiter = $delimiter
$query.TextFileParseType = 1
$query.TextFileColumnDataTypes = ,1 * $worksheet.Cells.Columns.Count
$query.AdjustColumnWidth = 1

# Execute & delete the import query
$query.Refresh()
$query.Delete()

# Save & close the Workbook as XLSX.
$Workbook.SaveAs($xlsx, 51)
$excel.Quit()

2 个答案:

答案 0 :(得分:1)

大多数时候,我使用模块ImportExcel(https://www.powershellgallery.com/packages/ImportExcel)将数据导入Excel或从Excel导出数据。它比com界面快得多。这使我的解决方案成为了2线制

(Get-Content .\sample.csv) -replace '&',"`r`n" |Set-Content .\sample.csv
Import-Csv .\sample.csv -Delimiter '|' | Export-Excel -Path .\export2.xlsx -WorksheetName SHEET1

再次:您需要一个模块。即使未安装Excel也可以使用!

答案 1 :(得分:0)

不能将文本连接器的所有内容都放在一行上。您必须在脚本的开头添加一些代码才能使其正常工作。

$folder = 'c:\path\to\file'
$file = 'test.csv'
$delimiter = '|'
$lineseparator = '&'

$csvfile = Join-Path $folder $file

# step by step
$contents = Get-Content $csvfile -Raw
$replacedcontents = $contents -replace $lineseparator, "`r`n"
$replacedcontents | Out-File $csvfile -Force

# or use this oneliner
(Get-Content $csvfile -Raw) -replace $lineseparator, "`r`n" | Out-File $csvfile -Force

我曾经使用过`r`n(Windows标准,char 13和10),但它可能也可以仅与`n一起使用。