如何使用OLEDB查询excel列表或表?

时间:2012-05-05 17:55:25

标签: excel ado.net oledb

使用Excel 2010 OleDb driver和OleDbConnection我可以在电子表格中查询和操作工作表和命名范围,如下所示:

$cn = New-Object System.Data.OleDb.OleDbConnection $cnStr;
$cmd = $cn.CreateCommand()

$cmd.CommandText = "INSERT INTO [Some Named Range] (" + 
@"
    [Name], [Description], 
    [Type], [Val], 
) VALUES(
    'Justin', 'A Programmer', 
    'Senor Developer', 11
)"@
$cmd.ExecuteNonQuery();

$cmd.CommandText = "SELECT * FROM [Some WorkSheet$]"
$rdr = $cmd.ExecuteReader();
[PSObject[]] $data = [PSObject[]]@();
while ($rdr.Read()) {
    $row = @{}; 0..($rdr.FieldCount-1) | %{$row[$rdr.GetName($_)] = $rdr[$_]; }
    $data += New-Object PSObject -Property $row;
}

但是,表格的命名约定是什么,在Excel 2003中被称为列表?

2 个答案:

答案 0 :(得分:0)

您必须使用listobject / table的地址:

Dim Table as Excel.ListObject
dim TableAddress as String

Set Table = Worksheets("Some Worksheet").ListObjects("SomeTable")
TableAddress = Table.Range.Address(RowAbsolute:=False,ColumnAbsolute:=False)
...
$cmd.CommandText = "SELECT * FROM [Some WorkSheet$" TableAddress & "]"

答案 1 :(得分:0)

您无法使用OleDB或ODBC驱动程序执行此操作。