【问题标题】:Import CSV with row delimiters into Excel using PowerShell使用 PowerShell 将带有行分隔符的 CSV 导入 Excel
【发布时间】:2018-12-28 13:29:22
【问题描述】:

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

这是 CSV 文件的示例:

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

我找到了这个脚本,但仅在行分隔符为 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()

【问题讨论】:

  • 用新行替换 & (首先确保数据中没有 &)。
  • 我认为没有用于文本文件的数据库连接器,它不希望表行被换行符分隔。 Workbooks.Open()Workbooks.OpenText() 方法也只允许指定 column 分隔符,而不是 row 分隔符。替换输入文件中的行分隔符可能是您最好的选择。

标签: excel powershell csv


【解决方案1】:

大部分时间我使用模块 ImportExcel (https://www.powershellgallery.com/packages/ImportExcel) 将数据导入/导出 Excel。它比com接口快得多。这使我的解决方案成为 2-liner

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

再说一遍:你需要一个模块。即使没有安装 Excel 也能正常工作!

【讨论】:

    【解决方案2】:

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

    $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 标准,字符 13 和 10),但它也可能只适用于 `n

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-08-13
      • 2014-08-14
      • 2020-06-22
      • 1970-01-01
      • 2017-12-09
      • 2017-01-22
      相关资源
      最近更新 更多