Export-Csv cmdlet可以将数据导出为CSV文件,然后可以在Excel中导入。但是,我想要做的是将不同的CSV文件(具有不同的列定义)合并到一个具有多个工作表的Excel文件中(每个工作表不同)。
PowerShell可以直接调用Excel DLL并从CSV文件构建工作表吗?
答案 0 :(得分:12)
你可以用Excel.ComObject完成它,我有一个我创建的函数,你可以使用它,完全按照你的需要做到:
Function Merge-CSVFiles
{
Param(
$CSVPath = "C:\CSV", ## Soruce CSV Folder
$XLOutput="c:\temp.xlsx" ## Output file name
)
$csvFiles = Get-ChildItem ("$CSVPath\*") -Include *.csv
$Excel = New-Object -ComObject excel.application
$Excel.visible = $false
$Excel.sheetsInNewWorkbook = $csvFiles.Count
$workbooks = $excel.Workbooks.Add()
$CSVSheet = 1
Foreach ($CSV in $Csvfiles)
{
$worksheets = $workbooks.worksheets
$CSVFullPath = $CSV.FullName
$SheetName = ($CSV.name -split "\.")[0]
$worksheet = $worksheets.Item($CSVSheet)
$worksheet.Name = $SheetName
$TxtConnector = ("TEXT;" + $CSVFullPath)
$CellRef = $worksheet.Range("A1")
$Connector = $worksheet.QueryTables.add($TxtConnector,$CellRef)
$worksheet.QueryTables.item($Connector.name).TextFileCommaDelimiter = $True
$worksheet.QueryTables.item($Connector.name).TextFileParseType = 1
$worksheet.QueryTables.item($Connector.name).Refresh()
$worksheet.QueryTables.item($Connector.name).delete()
$worksheet.UsedRange.EntireColumn.AutoFit()
$CSVSheet++
}
$workbooks.SaveAs($XLOutput,51)
$workbooks.Saved = $true
$workbooks.Close()
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($workbooks) | Out-Null
$excel.Quit()
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($excel) | Out-Null
[System.GC]::Collect()
[System.GC]::WaitForPendingFinalizers()
}
更新CSV文件的路径,它将为文件夹中的每个CSV创建一个工作表,
像这样运行:
Merge-CSVFiles -CSVPath C:\CsvFolder -XLOutput C:\ExcelFile.xlsx