Powershell модуль import excel

PowerShell and Excel

Has the ImportExcel module helped you?

  • Made you look good to the boss?
  • Saved you time?
  • Made you more productive?

Consider donating. Thank you!

Donate

Build Status



Donate

Overview

Automate Excel with PowerShell without having Excel installed. Works on Windows, Linux and Mac. Creating Tables, Pivot Tables, Charts and much more just got a lot easier.

Examples ✨

Check out the more than 100 examples on ways to create amazing reports as well as make you more productive with PowerShell and Excel.

Basic Usage

Installation

Install-Module -Name ImportExcel

Create a spreadsheet

Here is a quick example that will create spreadsheet file from CSV data. Works with JSON, Databases, and more.

$data = ConvertFrom-Csv @"
Region,State,Units,Price
West,Texas,927,923.71
North,Tennessee,466,770.67
East,Florida,520,458.68
East,Maine,828,661.24
West,Virginia,465,053.58
North,Missouri,436,235.67
South,Kansas,214,992.47
North,North Dakota,789,640.72
South,Delaware,712,508.55
"@

$data | Export-Excel .salesData.xlsx

Read a spreadsheet

Quickly read a spreadsheet document into a PowerShell array.

$data = Import-Excel .salesData.xlsx

$data
Region State        Units Price
------ -----        ----- -----
West   Texas        927   923.71
North  Tennessee    466   770.67
East   Florida      520   458.68
East   Maine        828   661.24
West   Virginia     465   053.58
North  Missouri     436   235.67
South  Kansas       214   992.47
North  North Dakota 789   640.72
South  Delaware     712   508.55

Add a chart to spreadsheet

Chart generation is as easy as 123. Building charts based on data in your worksheet doesn’t get any easier.

Plus, it is automated and repeatable.

$data = ConvertFrom-Csv @"
Region,State,Units,Price
West,Texas,927,923.71
North,Tennessee,466,770.67
East,Florida,520,458.68
East,Maine,828,661.24
West,Virginia,465,053.58
North,Missouri,436,235.67
South,Kansas,214,992.47
North,North Dakota,789,640.72
South,Delaware,712,508.55
"@

$chart = New-ExcelChartDefinition -XRange State -YRange Units -Title "Units by State" -NoLegend

$data | Export-Excel .salesData.xlsx -AutoNameRange -ExcelChartDefinition $chart -Show

Add a pivot table to spreadsheet

Categorize, sort, filter, and summarize any amount data with pivot tables. Then add charts.

$data = ConvertFrom-Csv @"
Region,State,Units,Price
West,Texas,927,923.71
North,Tennessee,466,770.67
East,Florida,520,458.68
East,Maine,828,661.24
West,Virginia,465,053.58
North,Missouri,436,235.67
South,Kansas,214,992.47
North,North Dakota,789,640.72
South,Delaware,712,508.55
"@

$data | Export-Excel .salesData.xlsx -AutoNameRange -Show -PivotRows Region -PivotData @{'Units'='sum'} -PivotChartType PieExploded3D

Convert Excel data to other formats

Create a separate CSV file for each Excel sheet

Do you have an Excel file with multiple sheets and you need to convert each sheet to CSV file?

Problem Solved

The yearlyRetailSales.xlsx has 12 sheets of retail data for the year.

This single line of PowerShell converts any number of sheets in an Excel workbook to separate CSV files.

(Import-Excel .yearlyRetailSales.xlsx *).GetEnumerator() |
ForEach-Object { $_.Value | Export-Csv ($_.key + '.csv') }

Additional Resources

Videos

  • Export-Excel Hello World
  • Make Excel Data Pop
  • Slice And Dice Data
  • Lightning talk — PowerShell Excel Module

More Videos

  • Look smarter: deliver your work in Excel — James O’Neill @jamesoneill
  • Module Monday: ImportExcel — Adam Driscoll @adamdriscoll
  • Tutorials Excel Module Part 1
  • Tutorials Excel Module Part 2
  • Tutorials Excel Module Part 3
  • PowerShell Excel — Invoke-ExcelQuery
  • Powershell Excel — Data Validation
  • Creating Dashboards xPlatform

Articles

Title Author Twitter
More tricks with PowerShell and Excel James O’Neill @jamesoneill
Using the Import-Excel module: Part 1 Importing James O’Neill @jamesoneill
Using the Import Excel module part 2: putting data into .XLSx files James O’Neill @jamesoneill
Using the import Excel Module: Part 3, Pivots and charts, data and calculations James O’Neill @jamesoneill
Export AdventureWorksDW2017 to Excel for a Power BI Demo with Export-Excel Aaron Nelson @sqlvariant
Creating beautiful Powershell Reports in Excel Doug Finke @dfinke
PowerShell Excel and Conditional Formatting Doug Finke @dfinke
Learn to Automate Excel like a Pro with PowerShell Doug Finke @dfinke

Contributing

Contributions are welcome! Open a pull request to fix a bug, or open an issue to discuss a new feature or change.

Original README.md

Automate Excel with PowerShell without having Excel installedДанный материал является переводом оригинальной статьи «ATA Learning : Adam Bertram : PowerShell and Excel: Seize the Power!».

Microsoft Excel — один из тех вездесущих инструментов, от которых большинство из нас не может уйти, даже если хочет. Многие ИТ-специалисты используют Excel, как небольшую базу данных, в которой хранятся тонны данных в различных процедурах автоматизации. Каков наилучший сценарий автоматизации и Excel? Это, например, PowerShell!

Работу с таблицами Excel непросто автоматизировать. В отличие от менее функционального (и более простого) аналога файла CSV, книги Excel — это не просто текстовые файлы. Для работы со сложными книгами Excel потребует от PowerShell манипуляции с Component Object Model (COM), для чего раньше нужно было установить Excel. Однако, на самом деле, это вовсе не обязательно. Например, проницательный участник сообщества PowerShell, Doug Finke, создал модуль PowerShell, названный ImportExcel. Модуль устраняет сложность работы с Excel и позволяет легко работать с книгами Excel через PowerShell сценарии!

В этой статье рассмотрим пример того, что можно сделать в PowerShell и Excel с помощью модуля ImportExcel, а также рассмотрим несколько популярных вариантов использования.

Предварительные требования

При запуске модуля ImportExcel в системе Windows отдельные зависимости не требуются. Однако, если вы работаете с MacOS, вам необходимо установить пакет mono-libgdiplus, используя команду вида:

brew install mono-libgdiplus

Примечание: Все примеры в этой статье будут построены с использованием macOS, но все они должны работать и на других платформах. При использовании macOS, не забудьте перезапустить сеанс PowerShell, прежде чем продолжить.

Установка модуля ImportExcel

Начните с загрузки и установки модуля через PowerShell Gallery, запустив:

Install-Module ImportExcel -Scope CurrentUser

Через несколько секунд все будет в порядке.

Использование PowerShell для экспорта в рабочий лист Excel

Возможно, вы знакомы со стандартными командлетами PowerShell Export-Csv и Import-Csv. Эти командлеты позволяют читать и экспортировать объекты PowerShell в файлы CSV. К сожалению, в PowerShell нет таких же встроенных командлетов для Excel. Но, используя модуль ImportExcel, вы можете создать такой функционал!

Один из наиболее частых запросов системного администратора — это экспорт объектов PowerShell в рабочий лист Excel. С помощью командлета Export-Excel из модуля ImportExcel, вы можете легко сделать это. Командлет Export-Excel принимает любой объект точно так же, как делает Export-Csv. Этому командлету можно передать любой объект.

Например, возможно, вам нужно найти какие-то процессы, запущенные на вашем локальном компьютере, и поместить их в книгу Excel.

Чтобы найти процессы, запущенные в системе с помощью PowerShell, используйте командлет Get-Process, который возвращает каждый запущенный процесс и различную информацию о каждом процессе. Чтобы экспортировать эту информацию в Excel, используйте командлет Export-Excel, указывающий путь к создаваемой книге Excel. Вы можете увидеть пример команды и снимок экрана сгенерированного файла Excel ниже.

Get-Process | Export-Excel -Path './processes.xlsx

PowerShell command Export-Excel

Поздравляем! Вы экспортировали всю информацию точно так же, как Export-Csv, но, в отличие от Export-Csv, мы можем сделать эти данные намного интереснее. Убедитесь, что имя рабочего листа называется «Proccesses», данные находятся в таблице, а размер строк устанавливается автоматически.

Добавим к командлету параметр -AutoSize для автоматического изменения размера всех строк, -TableName, чтобы указать имя таблицы, которая будет включать все данные, и имя параметра -WorksheetName для процессов, и сможем увидеть на снимке экрана ниже, что в итоге получится.

Get-Process | Export-Excel -Path './processes.xlsx' -AutoSize -TableName 'Processes' -WorksheetName 'Proccesses'

PowerShell command Export-Excel as Table

Командлет Export-Excel имеет множество параметров, которые можно использовать для создания книг Excel всех видов. Для получения полной информации о возможностях Export-Excel, запустите:

Get-Help Export-Excel
Использование PowerShell для импорта в Excel

Итак, ранее вы экспортировали некоторую информацию в файл с именем process.xlsx. Возможно, теперь вам нужно переместить этот файл на другой компьютер и импортировать / прочитать эту информацию. Командлет Import-Excel к вашим услугам.

При простейшем использовании вам нужно только указать путь к документу / книге Excel с помощью параметра -Path, как показано ниже. Вы увидите, что он читает первый рабочий лист, в данном случае рабочий лист «Processes», и возвращает объекты PowerShell.

Import-Excel -Path './processes.xlsx'

PowerShell command Import-Excel

Может быть, у вас есть несколько листов в книге Excel? Вы можете прочитать конкретный рабочий лист с помощью параметра -WorkSheetname.

Import-Excel -Path './processes.xlsx' -WorkSheetname 'SecondWorksheet'

Вам нужно читать только определенные столбцы из рабочего листа Excel? Используйте параметр -HeaderName, чтобы указать только те параметры, которые вы хотите прочитать.

Import-Excel -Path './processes.xlsx' –WorkSheetname 'Processes' -HeaderName 'CPU','Handle'

Командлет Import-Excel имеет другие параметры, которые можно использовать для чтения книг Excel всех типов. Чтобы получить полное изложение всего, что может делать Import-Excel, запустите:

Get-Help Import-Excel
Использование PowerShell для получения (и установки) значений ячеек Excel

Теперь вы знаете, как читать весь лист Excel с помощью PowerShell. Но что, если вам нужно только одно значение ячейки? Технически вы можете использовать Import-Excel и отфильтровать нужное значение с помощью Where-Object, но это будет не слишком эффективно.

Вместо этого, используя командлет Open-ExcelPackage, вы можете «преобразовать» книгу Excel в объект PowerShell, который затем можно будет читать и изменять. Этот командлет аналогичен использованию New-Object -ComObject ‘Excel.Application’, если работать напрямую с COM-объектами.

Чтобы найти значение ячейки, сначала откройте книгу Excel, чтобы занести его в память. Затем выберите лист внутри книги.

$excel = Open-ExcelPackage -Path './processes.xlsx'
$worksheet = $excel.Workbook.Worksheets['Processes']

Этот процесс похож на способ открытия книг с помощью COM-объекта ‘Excel.Workbooks.Open’.

После того, как рабочий лист назначен переменной, вы можете перейти к отдельным строкам, столбцам и ячейкам. Возможно, вам нужно найти все значения ячеек в строке A1. Вам просто нужно сослаться на свойство ‘Cells’, указав индекс A1, как показано ниже.

$worksheet.Cells['A1'].Value

Вы также можете изменить значение ячеек на листе, присвоив другое значение, например:

$worksheet.Cells['A1'] = 'differentvalue'

Будучи хранимым в оперативной памяти, важно высвобождать пакет Excel с помощью командлета Close-ExcelPackage.

Close-ExcelPackage $excel
Конверсия Excel в файлы CSV с помощью PowerShell

Если у вас есть содержимое листа Excel, представленное с помощью объектов PowerShell, преобразование листов Excel в CSV просто требует отправки этих объектов в командлет Export-Csv.

Используя созданную ранее книгу processes.xlsx, прочтите первый рабочий лист, который получает все данные в объекты PowerShell, а затем экспортируйте эти объекты в CSV с помощью приведенной ниже команды.

Import-Excel './processes.xlsx' | Export-Csv -Path './processes.csv' -NoTypeInformation
Конверсия множества рабочих листов

Если у вас есть книга Excel с несколькими листами, вы также можете создать файл CSV для каждого листа. Для этого вы можете найти все листы в книге с помощью командлета Get-ExcelSheetInfo. Когда у вас есть имена рабочих листов, вы можете передать их в параметр -WorksheetName, а также использовать имя листа в качестве имени файла CSV.

Ниже вы можете найти необходимый пример кода.

$sheets = (Get-ExcelSheetInfo -Path './processes.xlsx').Name
foreach ($sheet in $sheets) {
 Import-Excel -WorksheetName $sheet -Path './processes.xlsx' | Export-Csv "./$sheet.csv" -NoTypeInformation
 }
Заключение

Используя модуль ImportExcel из библиотеки модулей PowerShell, вы можете импортировать, экспортировать и управлять данными в книгах Excel точно так же, как и в CSV, без установки Excel!

PowerShell into Excel - ImportExcel Module Part 1

While ago I needed to do some manipulation on Excel spreadsheets but had no Office installed on the server. For the specific case, I looked for a way to complete my task with PowerShell. A quick look into Google search results and…

Even though the name is not specified, both articles talk about the ImportExcel module (if you scroll down the results a bit you will see this link).

If you like the topic please have a look at the series of different usage scenarios.

Winter series of PowerShell and Excel

What is ImportExcel?

I will use Doug’s description from the GitHub repository:

This PowerShell Module allows you to read and write Excel files without installing Microsoft Excel on your system. No need to bother with the cumbersome Excel COM-object. Creating Tables, Pivot Tables, Charts and much more has just become a lot easier.

That’s right! No need to install Microsoft Excel.

I have recently tested the 7.1.0 version and it contains about 60 functions. Some of the functions are:

Add-ConditionalFormatting
Add-ExcelTable
Compare-Worksheet
ConvertFrom-ExcelToSQLInsert
Export-Excel
Import-Excel
Join-Worksheet
PieChart
Pivot

ImportExcel – quick start

Firstly, to get the module installed on my machine I have ran this short script:

# set the execution policy for the current process
Set-ExecutionPolicy Bypass -Scope Process
# install and import module
Install-Module -Name ImportExcel
Import-Module -Name ImportExcel
# confirm the module is installed
Get-Module -Name ImportExcel
<#
ModuleType Version    Name                                ExportedCommands                                                                                               
---------- -------    ----                                ----------------                                                                                               
Script     7.1.0      ImportExcel                         {Add-ConditionalFormatting, Add-ExcelChart, Add-ExcelDataValidationRule, Add-ExcelName...} 
#>

Secondly, let’s see what this tool can do! I would like to see all the commands from the module and export their names to the Excel spreadsheet:

# get all the functions from the module and export as a spreadsheet
Get-Command -Module ImportExcel | SELECT Name | Export-Excel

As a result, I am getting new Excel windows open with temporary name tmpF12D located in $env:TEMP with output formatted as a spreadsheet table Table1.

Exported file in Excel spreadsheet format with named range (Excel table)

That was easy, but I want to see more.

ImportExcel – how to?

I have created an Excel spreadsheet from PowerShell, but what else I could do?

ImportExcel – how to work with worksheets?

As a matter of fact the ImportExcel module allows to manipulate worksheets.

# go to the temporary location
Set-Location $env:TEMP
# load the spreadsheet
$filename = 'tmpF12D.xlsx'
$excel = Open-ExcelPackage -Path $filename
# add an extra sheet to the end
Add-Worksheet -ExcelPackage $excel -WorksheetName Mikey -MoveToEnd
# and save it back to the file and show the file
Close-ExcelPackage -ExcelPackage $excel -Show
<# 
Unfortunately getting an error:
Exception calling "Save" with "0" argument(s): "Error saving file C:UsersMikeyAppDataLocalTemptmpF12D.xlsx"
At C:UsersmichaMikeyOneDriveDocumentsWindowsPowerShellModulesImportExcel7.1.0PublicClose-ExcelPackage.ps1:27 char:29
+             else           {$ExcelPackage.Save()          }
+                             ~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : InvalidOperationException
#>

And the reason for that is simple – I had the file open. Therefore I am going to close it and repeat the above script:

# load the spreadsheet
$filename = 'tmpF12D.xlsx'
$excel = Open-ExcelPackage -Path $filename
# close the open file
([Runtime.InteropServices.Marshal]::GetActiveObject('Excel.Application').workbooks | Where-Object {$_.FullNameURLEncoded -eq $excel.File }).Close($false)
# similar effect would be using the KillExcel switch
# close WHOLE Excel app (not just the specific file) and load to variable
$excel = Open-ExcelPackage -Path $filename -KillExcel
# add an extra sheet to the end
Add-Worksheet -ExcelPackage $excel -WorksheetName Mikey -MoveToEnd
# and save it back to the file and show the file
Close-ExcelPackage -ExcelPackage $excel -Show

New sheet 'Mikey' has been added to our file.

As shown above, adding an empty sheet was amazingly easy (and I have learned a new thing about closing files). How about populating it with the data?

# load the spreadsheet
$filename = 'tmpF12D.xlsx'
$excel = Open-ExcelPackage -Path $filename
([Runtime.InteropServices.Marshal]::GetActiveObject('Excel.Application').workbooks | Where-Object {$_.FullNameURLEncoded -eq $excel.File }).Close($false)
# add new worksheet at the beginning
Add-Worksheet -ExcelPackage $excel -WorksheetName Process -MoveToStart
# get the data into a new sheet as a named table
# freeze the first row and column with an auto-sized length
Get-Process | Export-Excel -ExcelPackage $excel -WorksheetName Process -TableName Process -Show -AutoSize -FreezeTopRow -FreezeFirstColumn 

New sheet 'Process' has been added to our file.

Perfect, we have some data. Pivot? Why not.

ImportExcel – how to make pivot tables?

For example, using Add-PivotTable is straightforward (and from now on I am closing the whole Excel). Also, note the Activate switch at the end. When you open the Excel file the worksheet that was used in the command will show up first.

# load the spreadsheet
$filename = 'tmpF12D.xlsx'
$excel = Open-ExcelPackage -Path $filename -KillExcel
# add a simple pivot table
Add-PivotTable -ExcelPackage $excel -PivotRows Name -PivotColumns PriorityClass -PivotData @{'CPU' = 'sum'} -SourceWorkSheet process -PivotTableName 'Pivot' -Activate
# save it to the file and display
Close-ExcelPackage -ExcelPackage $excel -Show

Additionally, if something went wrong with our data and we need to recreate the pivot table. No problem. Drop the worksheet and create a new pivot table.

# load the spreadsheet
$filename = 'tmpF12D.xlsx'
$excel = Open-ExcelPackage -Path $filename -KillExcel
# drop the pivot table worksheet (using the filename, not the package)
Remove-Worksheet -FullName $filename -WorksheetName Pivot 
# add some more stuff to the pivot table
Add-PivotTable -ExcelPackage $excel -PivotRows Name -PivotColumns PriorityClass -PivotData @{'CPU' = 'sum'; 'Company' = 'count'} -SourceWorkSheet process -PivotTableName 'Pivot' -Activate -NoTotalsInPivot -PivotTableStyle Dark1
# save it to the file and display
Close-ExcelPackage -ExcelPackage $excel -Show

As a result of both operations we get two tables;

Simple pivot table added to the spreadsheet

Pivot table after some modifications

ImportExcel – how to make pivot table charts?

It is common to have a pivot table chart alongside the data. In fact, ImportExcel module supports that too.

# load the spreadsheet
$filename = 'tmpF12D.xlsx'
$excel = Open-ExcelPackage -Path $filename -KillExcel
# setup definition for the first pivot table; note the IncludePivotChart
$PTDef =  New-PivotTableDefinition -PivotTableName "P1" -SourceWorkSheet "Process" -PivotRows "Company" -PivotData @{'Cpu' = 'average'} -IncludePivotChart -ChartType BarClustered3D
# join the definition for the second pivot table
$PTDef += New-PivotTableDefinition -PivotTableName "P2" -SourceWorkSheet "Process" -PivotRows "Company" -PivotData @{'Cpu' = 'average'} -IncludePivotChart -ChartType Pie3D
# Export with the PivotTableDefinition
Export-Excel -ExcelPackage $excel -PivotTableDefinition $PTDef -Show -Activate

That does not limit the user to create pivot table charts on a new worksheet. It is quite simple to add more charts on the worksheet. Just to avoid overlapping of the charts and tables set the Address (for placing table [A]) and ChartRow / ChartColumn (to set location for a chart [B]).

# load the spreadsheet
$filename = 'tmpF12D.xlsx'
$excel = Open-ExcelPackage -Path $filename -KillExcel
# define parameters for another pivot table and chart
$PTParams = @{
    PivotTableName    = "P3"
    Address           = $excel.P2.cells["A22"] # top-left corner of the table
    SourceWorkSheet   = $excel.Process
    PivotRows         = @("Company")
    PivotData         = @{'Cpu' = 'average'}
    PivotTableStyle   = 'Light21'
    IncludePivotChart = $true
    ChartType         = "BarClustered3D"
    ChartRow          = 22 # place the chart below row 22nd
    Activate          = $true
}
# add the objects
Add-PivotTable @PTParams -PassThru
# save it to the file and display
Close-ExcelPackage $excel -Show

Pivot table chart #3 added to the existing worksheet

Amazing! In fact, it would be a day-long session to show all the scenarios just for pivot tables and charts.

Summary

To sum up, ImportExcel PowerShell module has many features and it is a powerful task. I showed you today how to do basic operations on worksheets and pivot tables/charts. Next week will describe more about regular charts and conditional formatting.

Thank you,

Mikey

5.4.0

PowerShell module to import/export Excel spreadsheets, without Excel.

Check out the How To Videos https://www.youtube.com/watch?v=U3Ne_yX4tYo&list=PL5uoqS92stXioZw-u-ze_NtvSo0k0K0kq


Installation Options

  • Install Module

  • Azure Automation

  • Manual Download

Copy and Paste the following command to install this package using PowerShellGet More Info


Install-Module -Name ImportExcel -RequiredVersion 5.4.0

You can deploy this package directly to Azure Automation. Note that deploying packages with dependencies will deploy all the dependencies to Azure Automation. Learn More

Manually download the .nupkg file to your system’s default download location. Note that the file won’t be unpacked, and won’t include any dependencies. Learn More

Author(s)

Douglas Finke

Copyright

c 2015 All rights reserved.


Package Details


FileList


Version History

Version Downloads Last updated


7.8.4

560,040 12/11/2022


7.8.3

73,982 11/20/2022


7.8.2

85,557 10/22/2022


7.8.1

159,417 9/3/2022


7.8.0

121,924 7/16/2022


7.7.0

22,643 7/4/2022


7.6.0

39,271 6/17/2022


7.5.3

54,402 5/30/2022


7.5.2

70,149 5/4/2022


7.5.1

3,750 5/3/2022


7.5.0

9,408 4/30/2022


7.4.2

31,837 4/19/2022


7.4.1

279,747 12/11/2021


7.4.0

38,068 11/20/2021


7.3.1

12,842 11/13/2021


7.3.0

105,952 9/14/2021


7.2.2

60,424 7/30/2021


7.2.1

7,241 7/24/2021


7.2.0

475 7/24/2021


7.1.2

118,473 5/8/2021


7.1.1

276,853 7/11/2020


7.1.0

145,360 3/21/2020


7.0.1

111,110 12/21/2019


7.0.0

10,605 12/7/2019


6.5.3

9,084 11/23/2019


6.5.2

10,770 11/2/2019


6.5.1

28,115 8/31/2019


6.5.0

1,472 8/28/2019


6.2.4

3,616 8/21/2019


6.2.3

12,362 7/24/2019


6.2.2

13,094 7/5/2019


6.2.1

7,697 6/18/2019


6.2.0

2,795 6/12/2019


6.1.0

17,888 5/26/2019


6.0.0

22,587 4/12/2019


5.4.5

20,317 3/2/2019


5.4.4

21,295 1/5/2019


5.4.3

1,956 12/30/2018


5.4.2

14,377 12/8/2018


5.4.0
(current version)

16,181 11/3/2018


5.3.4

18,496 10/4/2018


5.3.3

441 10/3/2018


5.3.2

3,900 9/20/2018


5.3.1

308 9/20/2018


5.3.0

415 9/19/2018


5.2.0

13,746 8/18/2018


5.1.1

7,364 8/2/2018


5.1.0

1,765 7/30/2018


5.0.1

14,805 6/27/2018


5.0.0

10,405 6/15/2018


4.0.13

13,106 4/22/2018


4.0.12

2,532 4/10/2018


4.0.11

2,280 3/31/2018


4.0.10

3,241 3/15/2018


4.0.9

29,008 1/25/2018


4.0.8

17,401 11/25/2017


4.0.7

222 11/24/2017


4.0.6

203 11/24/2017


4.0.5

254 11/23/2017


4.0.4

2,881 10/30/2017


4.0.3

1,264 10/20/2017


4.0.2

1,986 10/3/2017


4.0.1

435 9/30/2017


4.0.0

1,804 9/12/2017


3.0.1

6,580 7/3/2017


3.0.0

1,427 6/16/2017


2.4.0

8,703 2/22/2017


2.3.0

633 2/14/2017


2.2.10

2,311 12/22/2016


2.2.9

2,861 10/1/2016


2.2.8

1,123 9/1/2016


2.2.7

1,890 7/1/2016


2.2.6

220 7/1/2016


2.2.5

966 6/1/2016


2.2.4

934 4/30/2016


2.2.3

430 4/18/2016


2.2.2

502 3/31/2016


2.2.1

288 3/26/2016


2.2.0

290 3/18/2016


2.1.3

419 3/2/2016


2.1.2

318 2/24/2016


2.1.1

230 2/24/2016


2.1

266 2/22/2016


2.0.1

224 2/22/2016


2.0

273 2/21/2016


1.99

265 2/18/2016


1.98

436 1/29/2016


1.97

318 1/18/2016


1.96

223 1/15/2016


1.94

238 1/14/2016


1.92

282 1/6/2016


1.91

220 1/6/2016


1.90

825 10/20/2015


1.83

234 10/15/2015


1.82

283 10/1/2015


1.81

225 9/30/2015


1.8

231 9/25/2015


1.7

265 9/11/2015


1.6

261 8/21/2015


1.5

293 7/9/2015


1.4

269 6/18/2015


1.3

256 5/25/2015


1.2

226 5/18/2015


1.1

231 5/17/2015


1.0

384 5/4/2015

Show less

Microsoft Excel is one of those ubiquitous tools most of us can’t escape even if we tried. Many IT professionals use Excel as a little database storing tons of data in various automation routines. What’s the best scenario for automation and Excel? PowerShell and Excel!

Excel spreadsheets have always been notoriously hard to script and automate. Unlike its less-featured (and simpler) CSV file counterpart, Excel workbooks aren’t just simple text files. Excel workbooks required PowerShell to manipulate complicated Component Object Model (COM) objects thus you had to have Excel installed. Not anymore.

Thankfully, an astute PowerShell community member, Doug Finke, created a PowerShell module called ImportExcel for us mere mortals. The ImportExcel module abstracts away all of that complexity. It makes it possible to easily manage Excel workbooks and get down to PowerShell scripting!

In this article, let’s explore what you can do with PowerShell and Excel using the ImportExcel module and a few popular use cases.

Prerequisites

When running the ImportExcel module on a Windows system, no separate dependencies are necessary. However, if you’re working on macOS, you will need to install the mono-libgdiplus package using brew install mono-libgdiplus. All examples in this article will be built using macOS but all examples should work cross-platform.

If you’re using macOS, be sure to restart your PowerShell session before continuing.

Installing the ImportExcel Module

Start by downloading and installing the module via the PowerShell Gallery by running Install-Module ImportExcel -Scope CurrentUser. After a few moments, you’ll be good to go.

Using PowerShell and Excel to Export to a Worksheet

You may be familiar with the standard PowerShell cmdlets Export-Csv and Import-Csv. These cmdlets allow you to read and export PowerShell objects to CSV files. Unfortunately, there’s no Export-Excel and Import-Excel cmdlets. But using the ImportExcel module, you can build your own functionality.

One of the most common requests a sysadmin has is exporting PowerShell objects to an Excel worksheet. Using the Export-Excel cmdlet in the ImportExcel module, you can easily make it happen.

For example, perhaps you need to find some processes running on your local computer and get them into an Excel workbook.

The Export-Excel cmdlet accepts any object exactly the way Export-Csv does. You can pipe any kind of object to this cmdlet.

To find processes running on a system with PowerShell, use the Get-Process cmdlet which returns each running process and various information about each process. To export that information to Excel, use the Export-Excel cmdlet providing the file path to the Excel workbook that will be created. You can see an example of the command and screenshot of the Excel file generated below.

Get-Process | Export-Excel -Path './processes.xlsx'
Worksheet created with PowerShell and Excel
Worksheet created with PowerShell and Excel

Congrats! You’ve now exported all the information just like Export-Csv but, unlike Export-Csv, we can make this data a lot fancier. Let’s make sure the worksheet name is called Processes, the data is in a table and rows are auto-sized.

By using the AutoSize switch parameter to autosize all rows, TableName to specify the name of the table that will include all the data and the WorksheetName parameter name of Processes, you can see in the screenshot below what can be built.

Get-Process | Export-Excel -Path './processes.xlsx' -AutoSize -TableName Processes -WorksheetName Proccesses
Autosize Switch Parameter Result
Autosize Switch Parameter Result

The Export-Excel cmdlet has a ton of parameters you can use to create Excel workbooks of all kinds. For a full rundown on everything Export-Excel can do, run Get-Help Export-Excel.

Using PowerShell to Import to Excel

So you’ve exported some information to a file called processes.xlsx in the previous section. Perhaps now you need to move this file to another computer and import/read this information with PowerShell and Excel. No problem. You have Import-Excel at your disposal.

At its most basic usage, you only need to provide the path to the Excel document/workbook using the Path parameter as shown below. You’ll see that it reads the first worksheet, in this case, the Processes worksheet, and returns PowerShell objects.

Import-Excel -Path './processes.xlsx'
Path Parameter
Path Parameter

Maybe you have multiple worksheets in an Excel workbook? You can read a particular worksheet using the WorksheetName parameter.

Import-Excel -Path './processes.xlsx' -WorkSheetname SecondWorksheet

Do you need to only read certain columns from the Excel worksheet? Use the HeaderName parameter to specify only those parameters you’d like to read.

Import-Excel -Path './processes.xlsx' -WorkSheetname Processes -HeaderName 'CPU','Handle'

The Import-Excel cmdlet has other parameters you can use to read Excel workbooks of all kinds. For a full rundown on everything Import-Excel can do, run Get-Help Import-Excel.

Using PowerShell to Get (and Set) Excel Cell Values

You now know how to read an entire worksheet with PowerShell and Excel but what if you only need a single cell value? You technically could use Import-Excel and filter out the value you need with Where-Object but that wouldn’t be too efficient.

Instead, using the Open-ExcelPackage cmdlet, you can “convert” an Excel workbook into a PowerShell object which can then be read and manipulated. To find a cell value, first, open up the Excel workbook to bring it into memory.

$excel = Open-ExcelPackage -Path './processes.xlsx'

The Open-ExcelPackage is similar to using New-Object -comobject excel.application if working directly with COM objects.

Next, pick the worksheet inside of the workbook.

$worksheet = $excel.Workbook.Worksheets['Processes']

This process is similar to the COM object way of opening workbooks with excel.workbooks.open.

Once you have the worksheet assigned to a variable, you can now drill down to individual rows, columns, and cells. Perhaps you need to find all cell values in the A1 row. You simply need to reference the Cells property providing an index of A1 as shown below.

$worksheet.Cells['A1'].Value

You can also change the value of cells in a worksheet by assigning a different value eg. $worksheet.Cells['A1'] = 'differentvalue'

Once in memory, it’s important to release the Excel package using the Close-ExcelPackage cmdlet.

Close-ExcelPackage $excel

Converting Worksheets to CSV Files with PowerShell and Excel

Once you have the contents of an Excel worksheet represented via PowerShell objects, “converting” Excel worksheets to CSV simply requires sending those objects to the Export-Csv cmdlet.

Using the processes.xlsx workbook created earlier, read the first worksheet which gets all of the data into PowerShell objects, and then export those objects to CSV using the command below.

Import-Excel './processes.xlsx' | Export-Csv -Path './processes.csv' -NoTypeInformation

If you now open up the resulting CSV file, you’ll see the same data inside of the Processes worksheet (in this example).

Converting Multiple Worksheets

If you have an Excel workbook with multiple worksheets, you can also create a CSV file for each worksheet. To do so, you can find all the sheets in a workbook using the Get-ExcelSheetInfo cmdlet. Once you have the worksheet names, you can then pass those names to the WorksheetName parameter and also use the sheet name as the name of the CSV file.

Below you can the example code needed using PowerShell and Excel.

## find each sheet in the workbook
$sheets = (Get-ExcelSheetInfo -Path './processes.xlsx').Name
## read each sheet and create a CSV file with the same name
foreach ($sheet in $sheets) {
	Import-Excel -WorksheetName $sheet -Path './processes.xlsx' | Export-Csv "./$sheet.csv" -NoTypeInformation
}

Conclusion

Using PowerShell and Excel, you can import, export, and manage data in Excel workbooks exactly like you would CSVs without having to install Excel!

In this article, you learned the basics of reading and writing data in an Excel workbook but this just scratches the surface. Using PowerShell and the ImportExcel module, you can create charts, pivot tables, and leverage other powerful features of Excel!

Like this post? Please share to your friends:
  • Power quick excel скачать бесплатно
  • Powershell как закрыть excel
  • Powerpoint обновление связей с excel
  • Power quick excel 2016
  • Powershell выгрузка в excel