【发布时间】:2015-01-14 22:42:34
【问题描述】:
好的,是时候重新开始这个问题了。我找到了以下脚本http://blogs.technet.com/b/heyscriptingguy/archive/2010/09/09/copy-csv-columns-to-an-excel-spreadsheet-by-using-powershell.aspx
我的问题是如何让 powershell 为任意数量的 CSV 文件循环该脚本。脚本的速度并不重要。我收到了一些答案,它们在某种程度上存在问题。使用 Technet 脚本可提供正确的输出。
我想出了这个方法,但很难让代码循环遍历多个 CSV 文件。
Function Excel-Stuff {
[cmdletBinding()]
Param([Parameter(ValueFromPipeline=$true)][string]$junk)
$excel.cells.item(1,1) = "Server"
$excel.cells.item(1,2) = "Rack"
$excel.cells.item(1,3) = "Environment"
$excel.cells.item(1,4) = "RebootTime"
$excel.cells.item(1,5) = "Schedule"
$i = 2
$processes = Import-Csv 'C:\Monday.csv'
foreach ($process in $processes){
$excel.cells.item($i,1) = $process.Server
$excel.cells.item($i,2) = $process.Rack
$excel.cells.item($i,3) = $process.Environment
$excel.cells.item($i,4) = $process.RebootTime
$excel.cells.item($i,5) = $process.Schedule
$i++
} #end foreach process
$autofit = $Global:worksheet.UsedRange
$autofit.EntireColumn.AutoFit() | Out-Null
}#End Function.
$Excel = New-Object -ComObject excel.application
$workbook = $Excel.workbooks.add(1)
$Global:worksheet = $workbook.WorkSheets.Item(1)
$Global:worksheet.Name='Monday'
Excel-Stuff
$Excel.visible = $True
【问题讨论】:
-
这种方法很慢。您不能直接在 Excel 中打开 CSV 并将工作表复制到新工作簿吗?至于您遇到的错误:工作表对象没有
Worksheets属性(它们不包含其他工作表)。 -
我承认我只是对代码示例投掷飞镖,试图提出一些可行的方法。我还没有找到可以打开任意数量的 CSV 然后将它们移动到 Excel 并重命名工作表的示例代码。
标签: arrays excel function powershell csv