PowerShell能否生成包含多张工作表的普通Excel文件?
cmdlet可以将数据导出为CSV文件,然后将其导入Excel。但是,我想做的是将不同的CSV文件(具有不同的列定义)合并到一个包含多个工作表的Excel文件中(其中每个工作表都不同)PowerShell能否生成包含多张工作表的普通Excel文件?,excel,csv,powershell,Excel,Csv,Powershell,cmdlet可以将数据导出为CSV文件,然后将其导入Excel。但是,我想做的是将不同的CSV文件(具有不同的列定义)合并到一个包含多个工作表的Excel文件中(其中每个工作表都不同) PowerShell能否直接调用Excel DLL并从CSV文件构造工作表?您可以使用Excel.com对象: ## Excel must be installed for this function to work... Function Merge-CSVFiles { Param( $CSVPath =
PowerShell能否直接调用Excel DLL并从CSV文件构造工作表?您可以使用
Excel.com对象
:
## Excel must be installed for this function to work...
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
太棒了!非常感谢。欢迎,如果它能解决您的问题,请将其标记为答案