excel - 多个 csv 文件到一个 xlsx 文件,但使用 powershell 不同的工作表

标签 excel powershell

我有 20 个 csv 文件。每个都是无关的。如何将它们组合成一个包含 20 张的 xlsx 文件,每张都以 csv 文件命名。

$root = "C:\Users\abc\Desktop\testcsv"
$CSVfiles = Get-ChildItem -Path $root -Filter *.csv

$xlsx = "C:\Users\abc\Desktop\testxl.xlsx" #output location
$delimiter = "," #delimiter

#Create a excel
$xl=New-Object -ComObject Excel.Application
$xl.Visible=$true
#add a workbook
$wb=$xl.WorkBooks.add(1)

ForEach ($csv in $CSVfiles){

    #name  the worksheet
    $ws=$wb.WorkSheets.item(1)
    $ws.Name = [io.path]::GetFileNameWithoutExtension($csv)

    $TxtConnector = ("TEXT;" + $csv)
    $Connector = $ws.QueryTables.add($TxtConnector,$ws.Range("A1"))
    $query = $ws.QueryTables.item($Connector.name)
    $query.TextFileOtherDelimiter = $delimiter
    $query.TextFileParseType  = 1
    $query.TextFileColumnDataTypes = ,1 * $ws.Cells.Columns.Count
    $query.AdjustColumnWidth = 1

    # Execute & delete the import query
    $query.Refresh()
    $query.Delete()
    $wb.SaveAs($xlsx,51)
}
# Save & close the Workbook as XLSX.
$xl.Quit()

最佳答案

This way ,将第一行更改为存储这 20 个 CSV 文件的文件夹,然后

$path="c:\path\to\folder" #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) + "_" + $env:USERNAME + "_combined-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

关于excel - 多个 csv 文件到一个 xlsx 文件,但使用 powershell 不同的工作表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49324636/

相关文章:

file - PowerShell Get-Content : Try{ .。 } 捕获 { ..}?

c# - 如何使用 ClosedXML 将数组插入 Excel 中的单行

json - 从JSON创建CSV文件时Powershell脚本性能不佳

regex - 为连续完整日志文件中的每个部分匹配 REGEX

VBA宏检查工作表名称是否存在

powershell - 如何使用单个命令加载自定义 powershell 配置文件

powershell - 如何使用 Powershell 从 DnsServerResourceRecord 获取真实的 RecordData?

java - 使用Spring MVC将Excel导入Mysql

excel - 27位二进制到十进制转换

python - 如何在Python中比较两个不同结构的Excel