随笔 - 24, 文章 - 0, 评论 - 1, 引用 - 0
数据加载中……

Reading an Excel sheet using PowerShell and ADO.Net

 

#Lets instantiate the objects we need:
$OleDbConn 
= New-Object "System.Data.OleDb.OleDbConnection"
$OleDbCmd 
= New-Object "System.Data.OleDb.OleDbCommand"
$OleDbAdapter 
= New-Object "System.Data.OleDb.OleDbDataAdapter"
$DataTable 
= New-Object "System.Data.DataTable" 

  

#
Set the connection string and connect. Please pay attention to the syntax, otherwise, you’ll get cryptic errors such as “Could not find installable ISAM”. Also, the file should not be locked exclusively
$OleDbConn.ConnectionString 
= "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\lognoulm\Desktop\servercfg.xls;Extended Properties=""Excel 8.0;HDR=YES"""
$OleDbConn.Open() 

  

#Optionally, 
to check that the connection is open, display the “State” property:
$OleDbConn.State 

  

#Now let’s construct a SQL query. Syntax 
for Excel is a little special, look at the end of this post for external references.
$OleDbCmd.Connection 
= $OleDbConn
$OleDbCmd.CommandText 
= "SELECT * FROM [Sheet1$]" 

  

#
Then set the Adapter object
$OleDbAdapter.SelectCommand 
= $OleDbCmd 

  

#
And then fill the DataTable object with the results
$OleDbAdapter.Fill($DataTable) 

  

#
If everything went fine, the command above will return the number of row present is the DataTable objectTo display the “raw” contents, just enter
$DataTable 

  

#
To show the first line (aka Row), use this $DataTable.Rows[0]
And how to display a given field in that row? Just use the field header. In my XLS, one header is for example “Name”
$DataTable.Rows[
0].Name 

 

摘自:http://www.marc-antho-etc.net/blog/post/Repost-Reading-an-Excel-sheet-using-PowerShell-and-ADONet.aspx

posted on 2009-04-14 10:38 nicktang 阅读(304) 评论(0)  编辑 收藏 引用 所属分类: Powershell

只有注册用户登录后才能发表评论。