gpt4 book ai didi

excel - PowerShell 可以生成包含多个工作表的纯 Excel 文件吗?

转载 作者:行者123 更新时间:2023-12-04 20:08:19 25 4
gpt4 key购买 nike

Export-Csv cmdlet 可以将数据导出为 CSV 文件,然后可以将其导入 Excel。但是,我想做的是将不同的 CSV 文件(具有不同的列定义)合并到一个具有多张工作表(每张工作表不同)的 Excel 文件中。

PowerShell 可以直接调用 Excel DLL 并从 CSV 文件构造工作表吗?

最佳答案

您可以使用 Excel.ComObject :

## 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

关于excel - PowerShell 可以生成包含多个工作表的纯 Excel 文件吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31183106/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com