使用Powershell将多个csv文件转换为多个工作簿的Excel文件
从SQLSERVER数据库通过脚本将数据导出成为CSV文件后,就需要将数据合并为多个工作簿的Excel文件,具体代码如下,大家可以参阅一下。
$path="D:\TestFold" #target folder
cd $path;
$csvs = Get-ChildItem .\* -Include *.csv
$y=$csvs.Count
Write-Host "Detected the following CSV files: ($y)"
foreach ($csv in $csvs)
{
Write-Host "—"$csv.Name
}
$outputfilename = $(get-date -f yyyyMMdd) + "_" + "-data.xlsx" #creates file name with date/username
Write-Host Creating: $outputfilename
$excelapp = new-object -comobject Excel.Application
$excelapp.sheetsInNewWorkbook = $csvs.Count
$xlsx = $excelapp.Workbooks.Add()
$sheet=1
foreach ($csv in $csvs)
{
$row=1
$column=1
$worksheet = $xlsx.Worksheets.Item($sheet)
$worksheet.Name = $csv.Name
$file = (Get-Content $csv)
foreach($line in $file)
{
$linecontents=$line -split ',(?!\s*\w+")'
foreach($cell in $linecontents)
{
$worksheet.Cells.Item($row,$column) = $cell
$column++
}
$column=1
$row++
}
$sheet++
}
$output = $path + "\" + $outputfilename
$xlsx.SaveAs($output)
$excelapp.quit()
cd \ #returns to drive root
本作品采用 知识共享署名-相同方式共享 4.0 国际许可协议 进行许可。
评论已关闭