How To Read Data From Excel Using PnP PowerShell

In this article, we are going to see how to read data from an Excel file using PnP-PowerShell. To achieve this, we use COM Interface. Before starting, we need to gain a little knowledge of each layer. The first layer will be an application layer that contains one or more workbooks and each workbook contains one or more worksheets. In each worksheet, you can access the data using range.


Application Layer

Application layer is the top class layer on which we can open the new instance for the Excel application on the computer.

  1. $execelobj = New-Object -comobject Excel.Application  


 WorkBook Layer

In WorkBook layer, you are going to open the workbook inside the Excel instance.


We can verify if the workbook is opened, using the following line.

  1. $excelObj.Workbooks | Select-Object -Property name, author, path   


Then, see the properties and methods that can be used.

  1. $excelObj.Workbooks | Get-Member  


In the following example, I hold the date inside the $workBook variable.

  1. $workBook = $excelObj.Workbooks.Open("F:\Ravishankar\email_details.xlsx")  

WorkSheet Layer

In WorkSheet layer, you can list the worksheets inside the workbooks by using the below code snippet.

  1. $workBook.sheets | Select-Object -Property Name   


You can select the worksheet by using the below code.

  1. $workSheet = $workBook.Sheets.Item("emails")  

Range Layer

In Range layer, you can get the values from Excel. There are many ways to select values from a worksheet, as given below.

  1. $workSheet.Range("A1").Text  
  2. $workSheet.Range("A1:A1").Text  
  3. $workSheet.Range("A1","A1").Text  
  4. $workSheet.cells.Item(1, 1).text  
  5. $workSheet.cells.Item(1, 1).value2  
  6. $workSheet.Columns.Item(1).Rows.Item(1).Text  
  7. $workSheet.Rows.Item(1).Columns.Item(1).Text  


 Final code

  1. $filePath ="F:\Ravishankar\Deployment\PSHELL\PSHELL\email_details.xlsx"  
  2. # Create an Object Excel. Application using Com interface  
  3. $excelObj = New-Object -ComObject Excel.Application  
  4. # Disable the 'visible' property so the document won't open in excel  
  5. $excelObj.Visible = $false  
  6. #open WorkBook  
  7. $workBook = $excelObj.Workbooks.Open($filePath)  
  8. #Select worksheet using Index  
  9. $workSheet = $workBook.sheets.Item(1)  
  10. #Select the range of rows should read  
  11. $range= 3  
  12. for($i=1;$i-le $range;$i++){  
  13.    $workSheet.Columns.Item(1).Rows.Item($i).Text  
  14. }  

Hope you have learned how to read the data from Excel programmatically using PnP PowerShell scripting. Feel free to fill up the comment box below if you need any assistance.

Similar Articles