繁体   English   中英

POWERSHELL如何将几个csv合并为一个excel

[英]POWERSHELL how to combine several csv into one excel

我正在尝试使用 PS 脚本从\tmp\目录下载所有 CSV 文件,并将它们转换为一个 excel 文件作为报告,并将其放置在名称LDAP.xlsx下的\reports\目录中。 我的 CSV 文件有不同数量的保存数据。

在论坛中,我发现了这个how-to-export-a-csv-to-excel-using-powershell ,我的代码如下所示:

Clear-Host
# SOURCE
##########
# config file
$conf_file = "C:\PS_LDAP_searchlight\config\searchlight_conf.conf"
$conf_values = Get-Content $conf_file | Out-String | ConvertFrom-StringData

# variables from config file
$main_path = $conf_values.main_path
$tmp_path = $conf_values.tmp_path
$reports_path = $conf_values.reports_path

# PROGRAM
##########
$workingdir = $main_path + $tmp_path + "*.csv"
$reportsdir = $main_path + $reports_path
$csv = dir -path $workingdir
foreach($inputCSV in $csv){
$outputXLSX = $reportsdir + "\" + $inputCSV.Basename + ".xlsx"
### Create a new Excel Workbook with one empty sheet
$excel = New-Object -ComObject excel.application 
$excel.DisplayAlerts = $False
$workbook = $excel.Workbooks.Add(1)
$worksheet = $workbook.worksheets.Item(1)
### Build the QueryTables.Add command
### QueryTables does the same as when clicking "Data » From Text" in Excel
$TxtConnector = ("TEXT;" + $inputCSV)
$Connector = $worksheet.QueryTables.add($TxtConnector,$worksheet.Range("A1"))
$query = $worksheet.QueryTables.item($Connector.name)
### Set the delimiter (, or ;) according to your regional settings
### $Excel.Application.International(3) = ,
### $Excel.Application.International(5) = ;
$query.TextFileOtherDelimiter = $Excel.Application.International(5)
### Set the format to delimited and text for every column
### A trick to create an array of 2s is used with the preceding comma
$query.TextFileParseType  = 1
$query.TextFileColumnDataTypes = ,2 * $worksheet.Cells.Columns.Count
$query.AdjustColumnWidth = 1
### Execute & delete the import query
$query.Refresh()
$query.Delete()
### Save & close the Workbook as XLSX. Change the output extension for Excel 2003
$Workbook.SaveAs($outputXLSX,51)
$excel.Quit()

# Cleaner
$inputCSV = $null
$outputXLSX = $null

}
## To exclude an item, use the '-exclude' parameter (wildcards if needed)
#remove-item -path $workingdir -exclude *Crab4dq.csv

# CLEANER
###############################
# SOURCE
###############################
# config file
    $conf_file = $null
    $conf_values = $null
# variables from config file
    $main_path = $null
    $tmp_path = $null
    $reports_path = $null
# PROGRAM
###############################
    $workingdir = $null
    $csv = $null
    $reportsdir = $null

该代码读取所有文件,但一对一写入。 我需要有关如何进行多对一选择的帮助和解释。 我希望每个 CSV 文件以其自己的名称保存为单独的工作表,例如:

excel\sheet1 中的 users_all_inf.csv => users_all_inf
excel\sheet2 中的 active_users_last_logon_year_ago.csv => active_users_last_logon_year_ago
excel\next_sheet 中的下一个文件名.csv => 下一个文件名

这样所有数据都将在一个 excel report.xlsx 文件中可用。
对于转换代码的任何提示或帮助,我将不胜感激。

最后我的代码看起来像:

Clear-Host
# config file
$conf_file = "C:\SEARCHLIGHT\config\searchlight_conf.conf"
$conf_values = Get-Content $conf_file | Out-String | ConvertFrom-StringData

# variables from config file
$main_path = $conf_values.main_path
$tmp_path = $conf_values.tmp_path
$reports_path = $conf_values.reports_path
$system_name = $conf_values.system_name

$tmp_dir = $main_path + $tmp_path + "*" # source file
$outputfilename = $(get-date -f yyyyMMdd) + "_" + $system_name + "_report.xlsx" # destination file with date
    
# get list of csvs files
$csvs = Get-ChildItem $tmp_dir -Include *.csv
$y = $csvs.Count
Write-Host "Detected the following CSV files: ($y)"
foreach ($csv in $csvs) {
    Write-Host " "$csv.Name
}

Write-Host Creating: $outputfilename
# Create a new Excel workbook
$excelapp = new-object -comobject Excel.Application
$excelapp.sheetsInNewWorkbook = $csvs.Count
$xlsx = $excelapp.Workbooks.Add()
$sheet=1
$delimiter = ";" # delimiter used in the csv file
foreach ($csv in $csvs) {
    #$row=1
    #$column=1
    $worksheet = $xlsx.Worksheets.Item($sheet)
    $worksheet.Name = $csv.Name
    # Build the QueryTables.Add command and reformat the data
    $TxtConnector = ("TEXT;" + $csv)
    $Connector = $worksheet.QueryTables.add($TxtConnector,$worksheet.Range("A1"))
    $query = $worksheet.QueryTables.item($Connector.name)
    $query.TextFileOtherDelimiter = $delimiter
    $query.TextFileParseType = 1
    $query.TextFileColumnDataTypes = ,1 * $worksheet.Cells.Columns.Count
    $query.AdjustColumnWidth = 1
    # Execute & delete the import query
    $query.Refresh()
    $query.Delete()
    $sheet++
} # end foreach ($csv in $csvs)
# Save & close the Workbook as XLSX
$output = $main_path + $reports_path + $outputfilename
$xlsx.SaveAs($output)
$excelapp.quit()

我找到了部分解决我的问题的解决方案:

# variables from config file
$main_path = $conf_values.main_path
$tmp_path = $conf_values.tmp_path
$reports_path = $conf_values.reports_path
$system_name = $conf_values.system_name

$tmp_dir = $main_path + $tmp_path + "*"
$csvs = Get-ChildItem $tmp_dir -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) + "_" + $system_name + "_report.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 = $main_path + $reports_path + $outputfilename
$xlsx.SaveAs($output)
$excelapp.quit()

这解决了多对一的问题,但在工作表中,所有数据都存储在一列中。 此时我有:csv个文件:

data1;data2;data3;...
data1;data2;data3;...

报告如:

|            A          | B |
|-----------------------|---|
| data1;data2;data3;... |   |
|-----------------------|---|
| data1;data2;data3;... |   |

我需要帮助将数据拆分成如下列:

|   A   |   B   |   C   | ... |
|-------|-------|-------|-----|
| data1 | data2 | data3 | ... |
|-------|-------|-------|-----|
| data1 | data2 | data3 | ... |

请找到有关使用 ImportExcel 模块的 github 链接。 https://github.com/dfinke/ImportExcel/tree/master/Examples

$outputFile = "C:\Temp\OutputExcelFile.xlsx" #Output File
$csvFiles = Get-childItem -Filter *.csv # Filtering CSV file in my present working dir
foreach ($csvFile in $csvFiles) {
#Import csv file and export it contents to Output excel file and rename the sheet.
Import-csv $csvFile | Export-Excel $outputFile -WorksheetName $csvFile.BaseName
}

希望能帮助到你。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM