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!
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 | |
---|---|---|
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
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 |
---|---|---|
|
560,040 | 12/11/2022 |
|
73,982 | 11/20/2022 |
|
85,557 | 10/22/2022 |
|
159,417 | 9/3/2022 |
|
121,924 | 7/16/2022 |
|
22,643 | 7/4/2022 |
|
39,271 | 6/17/2022 |
|
54,402 | 5/30/2022 |
|
70,149 | 5/4/2022 |
|
3,750 | 5/3/2022 |
|
9,408 | 4/30/2022 |
|
31,837 | 4/19/2022 |
|
279,747 | 12/11/2021 |
|
38,068 | 11/20/2021 |
|
12,842 | 11/13/2021 |
|
105,952 | 9/14/2021 |
|
60,424 | 7/30/2021 |
|
7,241 | 7/24/2021 |
|
475 | 7/24/2021 |
|
118,473 | 5/8/2021 |
|
276,853 | 7/11/2020 |
|
145,360 | 3/21/2020 |
|
111,110 | 12/21/2019 |
|
10,605 | 12/7/2019 |
|
9,084 | 11/23/2019 |
|
10,770 | 11/2/2019 |
|
28,115 | 8/31/2019 |
|
1,472 | 8/28/2019 |
|
3,616 | 8/21/2019 |
|
12,362 | 7/24/2019 |
|
13,094 | 7/5/2019 |
|
7,697 | 6/18/2019 |
|
2,795 | 6/12/2019 |
|
17,888 | 5/26/2019 |
|
22,587 | 4/12/2019 |
|
20,317 | 3/2/2019 |
|
21,295 | 1/5/2019 |
|
1,956 | 12/30/2018 |
|
14,377 | 12/8/2018 |
|
16,181 | 11/3/2018 |
|
18,496 | 10/4/2018 |
|
441 | 10/3/2018 |
|
3,900 | 9/20/2018 |
|
308 | 9/20/2018 |
|
415 | 9/19/2018 |
|
13,746 | 8/18/2018 |
|
7,364 | 8/2/2018 |
|
1,765 | 7/30/2018 |
|
14,805 | 6/27/2018 |
|
10,405 | 6/15/2018 |
|
13,106 | 4/22/2018 |
|
2,532 | 4/10/2018 |
|
2,280 | 3/31/2018 |
|
3,241 | 3/15/2018 |
|
29,008 | 1/25/2018 |
|
17,401 | 11/25/2017 |
|
222 | 11/24/2017 |
|
203 | 11/24/2017 |
|
254 | 11/23/2017 |
|
2,881 | 10/30/2017 |
|
1,264 | 10/20/2017 |
|
1,986 | 10/3/2017 |
|
435 | 9/30/2017 |
|
1,804 | 9/12/2017 |
|
6,580 | 7/3/2017 |
|
1,427 | 6/16/2017 |
|
8,703 | 2/22/2017 |
|
633 | 2/14/2017 |
|
2,311 | 12/22/2016 |
|
2,861 | 10/1/2016 |
|
1,123 | 9/1/2016 |
|
1,890 | 7/1/2016 |
|
220 | 7/1/2016 |
|
966 | 6/1/2016 |
|
934 | 4/30/2016 |
|
430 | 4/18/2016 |
|
502 | 3/31/2016 |
|
288 | 3/26/2016 |
|
290 | 3/18/2016 |
|
419 | 3/2/2016 |
|
318 | 2/24/2016 |
|
230 | 2/24/2016 |
|
266 | 2/22/2016 |
|
224 | 2/22/2016 |
|
273 | 2/21/2016 |
|
265 | 2/18/2016 |
|
436 | 1/29/2016 |
|
318 | 1/18/2016 |
|
223 | 1/15/2016 |
|
238 | 1/14/2016 |
|
282 | 1/6/2016 |
|
220 | 1/6/2016 |
|
825 | 10/20/2015 |
|
234 | 10/15/2015 |
|
283 | 10/1/2015 |
|
225 | 9/30/2015 |
|
231 | 9/25/2015 |
|
265 | 9/11/2015 |
|
261 | 8/21/2015 |
|
293 | 7/9/2015 |
|
269 | 6/18/2015 |
|
256 | 5/25/2015 |
|
226 | 5/18/2015 |
|
231 | 5/17/2015 |
|
384 | 5/4/2015 |
Show less
Данный материал является переводом оригинальной статьи «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
Поздравляем! Вы экспортировали всю информацию точно так же, как Export-Csv, но, в отличие от Export-Csv, мы можем сделать эти данные намного интереснее. Убедитесь, что имя рабочего листа называется «Proccesses», данные находятся в таблице, а размер строк устанавливается автоматически.
Добавим к командлету параметр -AutoSize для автоматического изменения размера всех строк, -TableName, чтобы указать имя таблицы, которая будет включать все данные, и имя параметра -WorksheetName для процессов, и сможем увидеть на снимке экрана ниже, что в итоге получится.
Get-Process | Export-Excel -Path './processes.xlsx' -AutoSize -TableName 'Processes' -WorksheetName 'Proccesses'
Командлет Export-Excel имеет множество параметров, которые можно использовать для создания книг Excel всех видов. Для получения полной информации о возможностях Export-Excel, запустите:
Get-Help Export-Excel
Использование PowerShell для импорта в Excel
Итак, ранее вы экспортировали некоторую информацию в файл с именем process.xlsx. Возможно, теперь вам нужно переместить этот файл на другой компьютер и импортировать / прочитать эту информацию. Командлет Import-Excel к вашим услугам.
При простейшем использовании вам нужно только указать путь к документу / книге Excel с помощью параметра -Path, как показано ниже. Вы увидите, что он читает первый рабочий лист, в данном случае рабочий лист «Processes», и возвращает объекты PowerShell.
Import-Excel -Path './processes.xlsx'
Может быть, у вас есть несколько листов в книге 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!
The ImportExcel is a PowerShell module that allows you import to or export data directly from Excel spreadsheets without having Microsoft Excel installed on your computer. In this tutorial, you’ll learn to work with Import-Excel and Export-Excel. The ImportExcel module runs on Windows, Linux, or Mac and now can be used in Azure functions and GitHub Actions. Simply put, if you need to generate reports for work, you must learn this module.
Contents
- Importing data from Excel
- Export data to Excel
- Adding data to an existing spreadsheet
- Exporting data with formatting
- Creating charts
- Editing existing data in an Excel spreadsheet
- Conclusion and links
- Author
- Recent Posts
Mike Kanakos is a Cloud and Datacenter Microsoft MVP, tech blogger and PowerShell community leader. He writes about infrastructure management and cloud automation. You can follow Mike on his blog https://www.commandline.ninja or on Twitter at @MikeKanakos.
Doug Finke, a Microsoft MVP since 2009, builds and maintains the module. Doug is constantly improving the module and releases new module updates frequently. As of this writing, the module is at v7.1.3 and is continually being developed. His module is nearing 1 million downloads since its first release! Installing the module is a simple task with PowerShell code.
Install-Module -Name ImportExcel
Excel is not required to be installed for this module to work. The module installs a .net DLL named epplus.dll that allows the module to import Excel data or export to Excel format. This allows you to install the module on a server without having to install Office on the server.
Importing data from Excel
Getting started with the module is very easy. Let’s start by importing some data from Excel. In this first demo, I’ll be importing some simple data I have from a table in Excel.
Sample Excel table data for import
To import data, I use the Import-Excel cmdlet and specify the path. In this example, I will also save the data to a variable called «Fruit» for later use.
Import-Excel "c:tempExcelDemo.xlsx" -OutVariable Fruit
Excel data import in PowerShell
Now, we have a simple table with data organized in columns and rows. The table properties reveal that PowerShell has created a PSCustomObject with two note properties for the two columns.
Excel table properties
But what if I have a large table of data? I can specify which data gets imported without having to pull in the entire table. Let’s look at how that works.
I have created a new tab in my spreadsheet that contains all the process info from my machine. I have named the tab «Processes.» The spreadsheet has 69 columns of data. I could import all these columns and filter the data, but for this demonstration I just want the Name, ProcessName, CPU, and Memory columns.
Process info data in Excel
Using the Import-Excel cmdlet, I can pull in just the data I am interested in. Let’s pull in the columns I mentioned earlier (Name, ProcessName, CPU, and Memory). For this demo, I only want 6 rows of data. To accomplish this, I use the -ImportColumns, -StartRow and -EndRow parameters.
To pick the columns, I simply count columns from left to right in my spreadsheet starting at 1. I know you can’t see the full spreadsheet, but I have already counted out the columns that I need. To select the columns I want, I will need columns 1, 6, 12, and 46. But if I want to keep them in the order I mentioned above, then the order would have to be 1, 46, 12, and 6.
import-excel C:tempExcelDemo.xlsx -WorksheetName Processes -ImportColumns @(1, 46, 12, 6) -startrow 1 -endrow 7
Process info imported into PowerShell
Export data to Excel
As with the process of importing data, I can also export data to Excel easily with just one line of code. Let’s go back to my previous example: getting the process data. If I want to export all the process info on my machine, all I need to do is type one line:
Get-process | Export-Excel
This results in the Export-Excel cmdlet creating a spreadsheet. If I have Excel installed, it launches Excel and presents the file output to me.
Exporting data to Excel using default values
Notice that I didn’t specify a filename or any other formatting information. However, the Export-Excel cmdlet created the spreadsheet and applied some default formatting (see callout 2) and created a temporary file for me (callout 1).
Of course, I can choose a filename and path on export, if I so desire, by using the -path parameter and inputting a value like so:
Get-process | Export-Excel C:tempProcessList.xlsx
Adding data to an existing spreadsheet
At some point, you will need to add data to an existing spreadsheet. The -Append parameter adds data to an existing spreadsheet. I can specify a worksheet to add to with the -worksheet parameter or I can start a new worksheet with the same parameter but picking a new tab name.
So far, I have been working on a spreadsheet named «ExcelDemo.xlsx,» which contains the Fruit and Processes worksheets. I want to add a new tab named «People» and copy in data from a small table I created.
Table of person and city info saved to the People variable
Exporting this data to my existing Excel spreadsheet and creating a new worksheet would look like this:
$People | Export-Excel c:tempExcelDemo.xlsx -Append -WorksheetName "People"
People table export
This is easy and doesn’t require much code. Below, we can see the worksheet tabs that have been created from Export-Excel.
Excel worksheet tabs created by Export Excel
When you look at the table, you’ll see that it has none of the familiar Excel spreadsheet formatting. I would like to add some formatting to my data. Let me show you how this can be done.
Exporting data with formatting
The Export-Excel cmdlet offers many options for formatting my data on export. I’ll highlight a few options, but make sure you review the parameters available for the Export-Excel cmdlet for a full list of formatting options.
I would like to export the data again. This time, however, I will add a table style and a title for my table, and I would like the table title to be bold. This is possible with Export-Excel. The code used to do this is slightly different from the previous example:
$People | Export-Excel c:tempExcelDemo.xlsx -Append -WorksheetName "PeopleFormatted" -TableStyle Medium16 -title "Demo of Table Formatting" -TitleBold
Formatted version of the People table in Excel
You might wonder what the table style I selected (Medium16) in the last example is. The Export-Excel cmdlet has table styles built in that correspond to the table styles you see in Excel.
Export Excel table styles available
The table styles in Excel are the same. In the screen cap below, I clicked on the «Format As Table» at the top of the spreadsheet, which then displays the table styles. If you hover your mouse over a style, you’ll see some text that provides you the style details. The #1 callout is the style I hovered over. Notice that it says Medium16. This is how I got the name that I used in my previous code example for the table style parameter.
Corresponding Excel table styles
Creating charts
Export-Excel does more than just make spreadsheets. The cmdlet can export table data and turn that data into a chart inside an Excel spreadsheet. For my next example, I have created a table of some simple inventory items and sales data.
Sales data
I would like to chart these sales in a simple bar graph that depicts units sold. To do this, I need to define the properties I want for my table. To do this, I use the New-ExcelChartDefinition cmdlet.
$ChartData = New-ExcelChartDefinition -XRange Item -YRange TotalSold -ChartType ColumnClustered -Title "Total Fruit Sales"
This line of code defines my table properties, and it tells Excel what to use for the xValue in the chart. I first use the Item column, then, I define the yValue (I am using the TotalSold column). Then, I specify a chart type. There are 69 chart types available in the cmdlet, all of which correspond to the chart types in Excel. I chose the «ColumnClustered» type for my example.
I then add a chart title, although this is not required. These values are saved to a variable named $ChartData. The next piece to add to the export cmdlet is this chart definition:
$data | Export-Excel C:tempExcelDemo.xlsx -Append -WorksheetName FruitSalesChart -ExcelChartDefinition $ChartData -AutoNameRange -show -Title "Fruit Sales"
Let’s walk through this example. First, I send the $data variable to the Export-Excel cmdlet. The $data variable is our sales data. The syntax for Export-Excel is a continuation from my previous example. I export and append this to a spreadsheet named «ExcelDemo.xlsx.» I create new worksheet tab named FruitSalesChart. This is all code we saw in the previous examples.
Then, I am add in the chart definition I created earlier by calling the $ChartData variable. Finally, I tell Excel that I want an auto name range. The -show parameter auto opens the spreadsheet after I create it.
Fruit Sales exported to Excel as a table and chart
Editing existing data in an Excel spreadsheet
I find it so easy to export data from PowerShell to Excel that I default to the Export-Excel cmdlet for much of my work. However, you can also update individual data values in an existing spreadsheet. I will connect to the spreadsheet that I used in the previous examples. To connect, use the Open-ExcelPackage cmdlet.
$ExcelPkg = Open-ExcelPackage -Path "C:tempExcelDemo.xlsx"
I can start to work with the data after opening the file.
Spreadsheet info in PowerShell
The first five rows constitute the worksheet tabs I created earlier in the spreadsheet. I can view the data in any of the tabs with some simple code.
#Let's access the data in the "PeopleFormatted" worksheet $WorkSheet = $ExcelPkg.Workbook.Worksheets["PeopleFormatted"].Cells $WorkSheet[3,1] | select value Value ----- Jeremy $WorkSheet[3,2] | select value Value ----- Loxahatchee
The code above probably doesn’t make much sense without a visual reference. Have a look at this screen cap below, which should help explain the code.
In the first code example, I called $WorkSheet[3,1] . If you look at the Excel spreadsheet, «3» represents the 3rd row. «1» represents the first column (starting from left of column A).
In the second code example, I called $WorkSheet[3,2] which is Row 3, Column2 (column B in spreadsheet).
Example of accessing Excel data values
Inserting a new value into the Excel data cell is done with a similar set of code. I will replace the name «Jeremy» with the name «Robert».
$WorkSheet[3,1].Value = "Robert" $WorkSheet[3,1] | select value Value ----- Robert
It’s that easy to update a field in Excel! However, there’s one catch. This change I just made is still in memory inside PowerShell. The file needs to «closed» for the data to be written back into the file.
Close-ExcelPackage $ExcelPkg
Updated spreadsheet value
Conclusion and links
Today, I showed you how to import data from an Excel spreadsheet, create a spreadsheet, create a simple chart, and manipulate the imported data in an existing Excel spreadsheet. The ImportExcel module makes these tasks and others operations simple to complete.
I have touched upon a just few of the many complex tasks you can perform with this module. If you would like to learn more, please visit Doug Finke’s GitHub page for many more examples of demo code you can try for yourself. He has a page dedicated to FAQs and a thorough analysis on examples that you should definitely check out.
Subscribe to 4sysops newsletter!
Many of the code examples in Doug’s module come from community members looking to use Excel in unique ways. If you have ideas for new ways to use his module, please submit a pull request to his repo so that others can learn from your use case.
Make Your CSV Output Look Nicer
The ImportExcel module is available in the PowerShell gallery. Maintained by MVP Doug Finke, the module allows developers to import and export data to Excel without needing to install the application on a workstation.
Although Microsoft 365 comes with some basic reports, many organizations use PowerShell scripts to generate reports covering anything from user activity to lists of mailboxes. Often, scripts use the Export-CSV cmdlet to export reports to CSV files. Later, people might use the CSV file to create a nicer report with Excel or import the data into Power BI. I cannot count the number of times I have been through this routine. On the input side, the Import-CSV cmdlet brings data into PowerShell for processing, such as a list of mailboxes to check.
Exporting to Excel
To check out the ImportExcel module, I used some of the reporting scripts I have discussed here over the years. After consulting the FAQ, I started by using the script to report the storage used by OneDrive for Business sites to generate a report, which is in a PowerShell list called $Report. To export to Excel (and have Excel start with the data loaded if the application is available), all I need to do is:
$Report | Export-Excel
Excel loads the data after applying the default table style (Figure 1).
To export to a named spreadsheet, add its name to the command:
$Report | Export-Excel -Path c:TempOneDrive.xlsx
This kind of export doesn’t apply any formatting, so you end up with something like Figure 2.
Because Excel supports multiple worksheets in a workbook, you can add new worksheets to an existing workbook. For example:
$Report | Export-Excel -Path c:TempOneDrive.xlsx -Append -WorksheetName "New data"
A more sophisticated version of the command creates a workbook with a named sheet, named table, title, and a different style. The names of the available table styles are visible if you hover over the styles displayed in the Excel Format as Table option. Figure 3 shows the output of this command:
$Report | Export-Excel -Path c:TempOneDrive.xlsx -WorksheetName "May 2022" -Title "OneDrive for Business Storage Consumption" -TitleBold -TableName "OneDriveStorage" -TableStyle Dark1
Charts
One of Excel’s most popular features is its ability to generate a variety of charts from spreadsheet data. To create a chart in a worksheet, we first define the kind of chart to generate in a variable and then export the data using the chart definition. Here’s how I created a pie chart (Figure 4) of the OneDrive storage data.
$ExcelChart = New-ExcelChartDefinition -XRange Owner -YRange UsedGB -ChartType Pie -Title "OneDrive for Business Storage" $Report | Export-Excel -Path c:tempOneDrive.xlsx -Append -WorksheetName "Pie Chart" -ExcelChartDefinition $ExcelChart -AutoNameRange -Show -Title "OneDrive for Business Storage"
Some trial and error are necessary to select the chart type from the set supported by Excel, but it’s easy enough to figure out.
Teams Membership
The ImportExcel module handled any of the reports I used as input. For instance, the output from the Microsoft 365 and Teams Membership Report script can grow to be pretty large, but ImportExcel had no problems. I generated the report shown in Figure 5 with this command:
$SummaryData | Export-Excel -Path c:TempTeamMembership.xlsx -WorksheetName "Groups May 2022" -Title "Microsoft 365 Groups and Teams Membership" -TitleBold -TableName "GroupsMembership" -TableStyle Medium28
Importing from Excel
Importing from Excel is like using the Import-CSV cmdlet, but with some extra controls. In this example, I identify what columns to import and a starting row.
[array]$Data = Import-Excel -Path c:tempTeamMembership.xlsx -ImportColumns @(1,2,3,4,5) -StartRow 2
Once loaded into the array, you can interact with the data using standard PowerShell commands. For instance, this code loops through the data to highlight users with “red” in their name:
ForEach ($D in $Data) { If ($D.User -like "*Red*") { Write-Host ("{0} is a member of {1} groups..." -f $D.User, $D."Groups count" ) } }
Updating Excel
Having some extra control over how you load data into PowerShell is interesting. Being able to interact with Excel data through Excel is more interesting. To do this, we use ImportExcel to load information for a worksheet in the target spreadsheet into a variable, and then use it to populate an array with information from the cells in the worksheet:
$ExcelData = Open-ExcelPackage -path c:tempTeamMembership.xlsx $Data = $ExcelData.Workbook.WorkSheets["Groups May 2022"].Cells
We can now navigate through cells using a row/column notation. For example, cell 3,1 (third row, first column) contains this information:
$Data[3,1] Style : OfficeOpenXml.Style.ExcelStyle StyleName : Normal StyleID : 0 Value : Tony Redmond Text : Tony Redmond Formula : FormulaR1C1 : Hyperlink : Merge : False AutoFilter : False IsRichText : False IsArrayFormula : False RichText : {} Comment : Worksheet : Groups May 2022 FullAddress : 'Groups May 2022'!A3 FullAddressAbsolute : 'Groups May 2022'!$A$3 ConditionalFormatting : OfficeOpenXml.ConditionalFormatting.RangeConditionalFormatting DataValidation : OfficeOpenXml.DataValidation.RangeDataValidation Current : Address : A3 Start : OfficeOpenXml.ExcelCellAddress End : OfficeOpenXml.ExcelCellAddress Table : IsName : False Rows : 1 Columns : 1
To update the cell, we write a new value into it, and when happy that the value is correct, close the Excel spreadsheet to save the data.
$Data[3,1].Value = “The Fool on the Hill” $Data[3,1] | Select -ExpandProperty Value The Fool on the Hill Close-ExcelPackage $ExcelData
Excel’s normal AutoSave functionality does not work, even when the spreadsheet location is on OneDrive for Business or a SharePoint Online site, so it’s important to remember to make changes and then save to commit, just like when working with files stored on local drives.
Worthwhile Toolkit Component
I like the ImportExcel module and think it brings a lot of useful functionality to the table. It’s an easy upgrade to apply formatting to CSV reports generated by scripts and certainly something worth considering, especially if the intended consumers of a report like charts.
Learn how to exploit the data available to Microsoft 365 tenant administrators through the Office 365 for IT Pros eBook. We love figuring out how things work.