【问题标题】:Writing a two-dimensional array to the Value2 property of an Excel range object in PowerShell在 PowerShell 中将二维数组写入 Excel 范围对象的 Value2 属性
【发布时间】:2012-10-07 22:00:59
【问题描述】:

我是 PowerShell 新手,似乎无法弄清楚为什么下面代码中的第一种方法不起作用,而第二种方法(已注释掉)却起作用。

我正在尝试将数据库记录集的结果写入 Excel 文件,因此我需要一个可动态扩展的数组。我知道如何使用第一种类型的数组,但不知道如何使用第二种类型。

如果满足以下条件,我的问题就会得到解决:

代码:

#need this to work around bug if you have a non us-locale and English excel: http://support.microsoft.com/default.aspx?scid=kb;en-us;320369
[System.Threading.Thread]::CurrentThread.CurrentCulture = "en-US" 

# This doesn't work
$values = @(('test1','test2'),('test3','test4'))

# This works
<#
$values = New-Object 'object[,]' 2,2
$values[0,0] = 'test1'
$values[0,1] = 'test2'
$values[1,0] = 'test3'
$values[1,1] = 'test4'
#>

$excel = New-Object -ComObject Excel.Application
$excel.Visible = $False
$xls_workbook = $excel.Workbooks.Add()
$range = $xls_workbook.sheets.item(1).Range("A1:B2")
$range.Value2 = $values

$xls_workbook.SaveAs($MyInvocation.MyCommand.Definition.Replace($MyInvocation.MyCommand.Name, "") + "test.xlsx")
$excel.Quit()

【问题讨论】:

    标签: excel powershell powershell-2.0


    【解决方案1】:

    当我得到两个变量的类型时:

    $values1.GetType() 
    $values2.GetType()
    

    这是我得到的:

    IsPublic IsSerial Name                                     BaseType                                                                                                               
    -------- -------- ----                                     --------                                                                                                               
    True     True     Object[]                                 System.Array                                                                                                           
    True     True     Object[,]                                System.Array   
    

    所以 $values1 是一维的,$values2 是二维的。这里有一个相关的问题:

    Powershell Multidimensional Arrays

    【讨论】:

    【解决方案2】:

    **Object[]** 是锯齿状数组或数组数组

    **Object[,]** 是二维数组。

    区别"in nutshell"

    还有How to convert jagged>2d arrays

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-04-07
      • 1970-01-01
      • 2015-05-22
      • 1970-01-01
      • 2020-03-27
      • 1970-01-01
      • 2022-12-18
      • 1970-01-01
      相关资源
      最近更新 更多