簡體   English   中英

使用powershell將csv文件轉換為excel

[英]convert csv file to excel using powershell

我正在嘗試使用 powershell 將 csv 文件轉換為 excel。 我從另一篇文章中得到了一些幫助,腳本運行了,但輸出是一個空白的 xlsx 文件。

有人可以幫忙嗎?

這是powershell腳本

param (
[Parameter(Mandatory=$true)][string]$inputfile,
[Parameter(Mandatory=$true)][string]$outputfile
)

$excel = New-Object -ComObject Excel.Application
$excel.Visible = $false

$wb = $excel.Workbooks.Add()
$ws = $wb.Sheets.Item(1)

$ws.Cells.NumberFormat = "@"

write-output "Opening $inputfile"

$i = 1
Import-Csv $inputfile | Foreach-Object { 
$j = 1
foreach ($prop in $_.PSObject.Properties)
{
    if ($i -eq 1) {
        $ws.Cells.Item($i, $j) = $prop.Name
    } else {
        $ws.Cells.Item($i, $j) = $prop.Value
    }
    $j++
}
$i++
}

$wb.SaveAs($outputfile,51)
$wb.Close()
$excel.Quit()
write-output "Success"

然后我運行以下命令

.\\csv_to_excel.ps1 -inputfile "C:\\Scripts\\testcsv.csv" -outputfile "C:\\Scripts\\data.xlsx"

另外,如果有人有使用導入 Excel powershell 模塊的經驗並有相關指南,我也將不勝感激。

謝謝

在裝有 PowerShell 5 或更低版本且安裝了PSGet的計算機上使用 Doug Finke 的 Excel 模塊:

Install-Module importexcel
Import-CSV $inputfile | Export-Excel $outputfile

$inputfile$outputfile是像你的腳本一樣的文件位置

#作為一個簡單的格式化方法的例子,只需使用“Export-Excel”

'Get-Service -ComputerName localhost |Select-Object -Property Status,Name,DisplayName|Export-Excel -Path '.\\output.xlsx'

#瞧!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM