Wednesday, September 13, 2023

Extract Data from Excel using powershell

----

1. This script opens an Excel file and reads data from a sheet named Sheet. 

2. Replace "SELECT * FROM [Sheet1$]" with the query that suits your needs.

3. Also, please ensure that the Microsoft.ACE.OLEDB.12.0 provider is installed on your machine, as it’s required to read data from Excel1.


```sh

#Read data from Excel
$cnStr = "Provider=Microsoft.ACE.OLEDB.12.0;Extended Properties='Excel 12.0;HDR=YES';Data Source=c:temptest.xlsx;Mode=Share Deny Write;Jet OLEDB:Engine Type=37;"
$cn = New-Object System.Data.OleDb.OleDbConnection $cnStr
$cn.Open()
$cmd = $cn.CreateCommand()
$cmd.CommandText = "SELECT * FROM [Sheet1$]"
$rdr = $cmd.ExecuteReader()
$dt = new-object System.Data.DataTable
$dt.Load($rdr)
$dt | Out-GridView


```
Please note that this script reads data from Excel using SQL,but it doesn’t extract SQL queries stored in Excel. 
If you have SQL queries stored in cells of an Excel sheet and you want to extract them, you would need to adjust the script to select those specific cells.

No comments:

Post a Comment