Powershell export excel module

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!

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

  1. Importing data from Excel
  2. Export data to Excel
  3. Adding data to an existing spreadsheet
  4. Exporting data with formatting
  5. Creating charts
  6. Editing existing data in an Excel spreadsheet
  7. 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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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.

avatar

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

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!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
function Export-Excel {
    <#

        .SYNOPSIS

            Exports data to an Excel worksheet.

        .DESCRIPTION

            Exports data to an Excel file and where possible tries to convert numbers

            in text fields so Excel recognizes them as numbers instead of text.

             After all: Excel is a spreadsheet program used for number manipulation

             and calculations. If number conversion is not desired, use the

             parameter -NoNumberConversion *.

        .PARAMETER Path

            Path to a new or existing .XLSX file.

        .PARAMETER ExcelPackage

            An object representing an Excel Package — usually this is returned by specifying -PassThru allowing multiple commands to work on the same workbook without saving and reloading each time.

        .PARAMETER WorksheetName

            The name of a sheet within the workbook — «Sheet1» by default.

        .PARAMETER ClearSheet

            If specified Export-Excel will remove any existing worksheet with the selected name. The Default behaviour is to overwrite cells in this sheet as needed (but leaving non-overwritten ones in place).

        .PARAMETER Append

            If specified data will be added to the end of an existing sheet, using the same column headings.

        .PARAMETER TargetData

            Data to insert onto the worksheet — this is usually provided from the pipeline.

        .PARAMETER DisplayPropertySet

            Many (but not all) objects have a hidden property named psStandardmembers with a child property DefaultDisplayPropertySet ; this parameter reduces the properties exported to those in this set.

        .PARAMETER NoAliasOrScriptPropeties

            Some objects duplicate existing properties by adding aliases, or have Script properties which take a long time to return a value and slow the export down, if specified this removes these properties

        .PARAMETER ExcludeProperty

            Specifies properties which may exist in the target data but should not be placed on the worksheet.

        .PARAMETER Calculate

            If specified a recalculation of the worksheet will be requested before saving.

        .PARAMETER Title

            Text of a title to be placed in the top left cell.

        .PARAMETER TitleBold

            Sets the title in boldface type.

        .PARAMETER TitleSize

            Sets the point size for the title.

        .PARAMETER TitleBackgroundColor

            Sets the cell background color for the title cell.

        .PARAMETER TitleFillPattern

            Sets the fill pattern for the title cell.

        .PARAMETER Password

            Sets password protection on the workbook.

        .PARAMETER IncludePivotTable

            Adds a PivotTable using the data in the worksheet.

        .PARAMETER PivotTableName

            If a PivotTable is created from command line parameters, specifies the name of the new sheet holding the pivot. Defaults to «WorksheetName-PivotTable».

        .PARAMETER PivotRows

            Name(s) of column(s) from the spreadsheet which will provide the Row name(s) in a PivotTable created from command line parameters.

        .PARAMETER PivotColumns

            Name(s) of columns from the spreadsheet which will provide the Column name(s) in a PivotTable created from command line parameters.

        .PARAMETER PivotFilter

            Name(s) columns from the spreadsheet which will provide the Filter name(s) in a PivotTable created from command line parameters.

        .PARAMETER PivotData

            In a PivotTable created from command line parameters, the fields to use in the table body are given as a Hash table in the form ColumnName = Average|Count|CountNums|Max|Min|Product|None|StdDev|StdDevP|Sum|Var|VarP.

        .PARAMETER PivotDataToColumn

            If there are multiple datasets in a PivotTable, by default they are shown as separate rows under the given row heading; this switch makes them separate columns.

        .PARAMETER NoTotalsInPivot

            In a PivotTable created from command line parameters, prevents the addition of totals to rows and columns.

        .PARAMETER PivotTotals

            By default, PivotTables have totals for each row (on the right) and for each column at the bottom. This allows just one or neither to be selected.

        .PARAMETER PivotTableDefinition

            Instead of describing a single PivotTable with multiple command-line parameters; you can use a HashTable in the form PivotTableName = Definition;

            Definition is itself a Hashtable with Sheet, PivotRows, PivotColumns, PivotData, IncludePivotChart and ChartType values.

        .PARAMETER IncludePivotChart

            Include a chart with the PivotTable — implies -IncludePivotTable.

        .PARAMETER ChartType

            The type for PivotChart (one of Excel’s defined chart types).

        .PARAMETER NoLegend

            Exclude the legend from the PivotChart.

        .PARAMETER ShowCategory

            Add category labels to the PivotChart.

        .PARAMETER ShowPercent

            Add percentage labels to the PivotChart.

        .PARAMETER ConditionalFormat

            One or more conditional formatting rules defined with New-ConditionalFormattingIconSet.

        .PARAMETER ConditionalText

            Applies a Conditional formatting rule defined with New-ConditionalText. When specific conditions are met the format is applied.

        .PARAMETER NoNumberConversion

            By default we convert all values to numbers if possible, but this isn’t always desirable. NoNumberConversion allows you to add exceptions for the conversion. Wildcards (like ‘*’) are allowed.

        .PARAMETER BoldTopRow

            Makes the top row boldface.

        .PARAMETER NoHeader

            Does not put field names at the top of columns.

        .PARAMETER RangeName

            Makes the data in the worksheet a named range.

        .PARAMETER TableName

            Makes the data in the worksheet a table with a name, and applies a style to it. Name must not contain spaces.

        .PARAMETER TableStyle

            Selects the style for the named table — defaults to ‘Medium6’.

        .PARAMETER BarChart

            Creates a «quick» bar chart using the first text column as labels and the first numeric column as values

        .PARAMETER ColumnChart

            Creates a «quick» column chart using the first text column as labels and the first numeric column as values

        .PARAMETER LineChart

            Creates a «quick» line chart using the first text column as labels and the first numeric column as values

        .PARAMETER PieChart

            Creates a «quick» pie chart using the first text column as labels and the first numeric column as values

        .PARAMETER ExcelChartDefinition

            A hash table containing ChartType, Title, NoLegend, ShowCategory, ShowPercent, Yrange, Xrange and SeriesHeader for one or more [non-Pivot] charts.

        .PARAMETER HideSheet

            Name(s) of Sheet(s) to hide in the workbook, supports wildcards. If the selection would cause all sheets to be hidden, the sheet being worked on will be revealed.

        .PARAMETER UnHideSheet

            Name(s) of Sheet(s) to reveal in the workbook, supports wildcards.

        .PARAMETER MoveToStart

            If specified, the worksheet will be moved to the start of the workbook.

            -MoveToStart takes precedence over -MoveToEnd, -Movebefore and -MoveAfter if more than one is specified.

        .PARAMETER MoveToEnd

            If specified, the worksheet will be moved to the end of the workbook.

            (This is the default position for newly created sheets, but this can be used to move existing sheets.)

        .PARAMETER MoveBefore

            If specified, the worksheet will be moved before the nominated one (which can be a position starting from 1, or a name).

            -MoveBefore takes precedence over -MoveAfter if both are specified.

        .PARAMETER MoveAfter

            If specified, the worksheet will be moved after the nominated one (which can be a position starting from 1, or a name or *).

            If * is used, the worksheet names will be examined starting with the first one, and the sheet placed after the last sheet which comes before it alphabetically.

        .PARAMETER KillExcel

            Closes Excel — prevents errors writing to the file because Excel has it open.

        .PARAMETER AutoNameRange

            Makes each column a named range.

        .PARAMETER StartRow

            Row to start adding data. 1 by default. Row 1 will contain the title if any. Then headers will appear (Unless -No header is specified) then the data appears.

        .PARAMETER StartColumn

            Column to start adding data — 1 by default.

        .PARAMETER FreezeTopRow

            Freezes headers etc. in the top row.

        .PARAMETER FreezeFirstColumn

            Freezes titles etc. in the left column.

        .PARAMETER FreezeTopRowFirstColumn

             Freezes top row and left column (equivalent to Freeze pane 2,2 ).

        .PARAMETER FreezePane

             Freezes panes at specified coordinates (in the form RowNumber, ColumnNumber).

        .PARAMETER AutoFilter

            Enables the Excel filter on the complete header row, so users can easily sort, filter and/or search the data in the selected column.

        .PARAMETER AutoSize

            Sizes the width of the Excel column to the maximum width needed to display all the containing data in that cell.

        .PARAMETER MaxAutoSizeRows

            Autosizing can be time consuming, so this sets a maximum number of rows to look at for the Autosize operation. Default is 1000; If 0 is specified ALL rows will be checked

        .PARAMETER Activate

            If there is already content in the workbook, a new sheet will not be active UNLESS Activate is specified; if a PivotTable is included it will be the active sheet

        .PARAMETER Now

            The -Now switch is a shortcut that automatically creates a temporary file, enables «AutoSize», «AutoFiler» and «Show», and opens the file immediately.

        .PARAMETER NumberFormat

            Formats all values that can be converted to a number to the format specified.

 
            Examples:

            # integer (not really needed unless you need to round numbers, Excel will use default cell properties).

            ‘0’

 
            # integer without displaying the number 0 in the cell.

            ‘#’

 
            # number with 1 decimal place.

            ‘0.0’

 
            # number with 2 decimal places.

            ‘0.00’

 
            # number with 2 decimal places and thousand-separator.

            ‘#,##0.00’

 
            # number with 2 decimal places and thousand-separator and money-symbol.

            ‘€#,##0.00’

 
            # percentage (1 = 100%, 0.01 = 1%)

            ‘0%’

 
            # Blue color for positive numbers and a red color for negative numbers. All numbers will be proceeded by a dollar sign ‘$’.

            ‘[Blue]$#,##0.00;[Red]-$#,##0.00’

 
        .PARAMETER ReZip

            If specified, Export-Excel will expand the contents of the .XLSX file (which is multiple files in a zip archive) and rebuild it.

        .PARAMETER NoClobber

            Not used. Left in to avoid problems with older scripts, it may be removed in future versions.

        .PARAMETER CellStyleSB

            A script block which is run at the end of the export to apply styles to cells (although it can be used for other purposes).

            The script block is given three paramaters; an object containing the current worksheet, the Total number of Rows and the number of the last column.

        .PARAMETER Show

            Opens the Excel file immediately after creation. Convenient for viewing the results instantly without having to search for the file first.

        .PARAMETER ReturnRange

            If specified, Export-Excel returns the range of added cells in the format «A1:Z100».

        .PARAMETER PassThru

            If specified, Export-Excel returns an object representing the Excel package without saving the package first.

            To save, you need to call Close-ExcelPackage or send the object back to Export-Excel, or use its .Save() or SaveAs() method.

        .EXAMPLE

            Get-Process | Export-Excel .Test.xlsx -show

            Export all the processes to the Excel file ‘Test.xlsx’ and open the file immediately.

 
        .EXAMPLE

        >

        PS> $ExcelParams = @{

                Path = $env:TEMP + ‘Excel.xlsx’

                Show = $true

                Verbose = $true

            }

            Remove-Item -Path $ExcelParams.Path -Force -EA Ignore

            Write-Output -1 668 34 777 860 -0.5 119 -0.1 234 788 |

                Export-Excel @ExcelParams -NumberFormat ‘[Blue]$#,##0.00;[Red]-$#,##0.00’

 
            Exports all data to the Excel file ‘Excel.xslx’ and colors the negative values

            in Red and the positive values in Blue. It will also add a dollar sign in front

            of the numbers which use a thousand seperator and display to two decimal places.

 
        .EXAMPLE

        >

        PS> $ExcelParams = @{

                Path = $env:TEMP + ‘Excel.xlsx’

                Show = $true

                Verbose = $true

            }

            Remove-Item -Path $ExcelParams.Path -Force -EA Ignore

            [PSCustOmobject][Ordered]@{

                Date = Get-Date

                Formula1 = ‘=SUM(F2:G2)’

                String1 = ‘My String’

                String2 = ‘a’

                IPAddress = ‘10.10.25.5’

                Number1 = ‘07670’

                Number2 = ‘0,26’

                Number3 = ‘1.555,83’

                Number4 = ‘1.2’

                Number5 = ‘-31’

                PhoneNr1 = ‘+32 44’

                PhoneNr2 = ‘+32 4 4444 444’

                PhoneNr3 = ‘+3244444444’

            } | Export-Excel @ExcelParams -NoNumberConversion IPAddress, Number1

 
            Exports all data to the Excel file «Excel.xlsx» and tries to convert all values

            to numbers where possible except for «IPAddress» and «Number1», which are

            stored in the sheet ‘as is’, without being converted to a number.

 
        .EXAMPLE

        >

        PS> $ExcelParams = @{

                Path = $env:TEMP + ‘Excel.xlsx’

                Show = $true

                Verbose = $true

            }

            Remove-Item -Path $ExcelParams.Path -Force -EA Ignore

            [PSCustOmobject][Ordered]@{

                Date = Get-Date

                Formula1 = ‘=SUM(F2:G2)’

                String1 = ‘My String’

                String2 = ‘a’

                IPAddress = ‘10.10.25.5’

                Number1 = ‘07670’

                Number2 = ‘0,26’

                Number3 = ‘1.555,83’

                Number4 = ‘1.2’

                Number5 = ‘-31’

                PhoneNr1 = ‘+32 44’

                PhoneNr2 = ‘+32 4 4444 444’

                PhoneNr3 = ‘+3244444444’

            } | Export-Excel @ExcelParams -NoNumberConversion *

 
            Exports all data to the Excel file ‘Excel.xslx’ as is, no number conversion

            will take place. This means that Excel will show the exact same data that

            you handed over to the ‘Export-Excel’ function.

 
        .EXAMPLE

        >

        PS> $ExcelParams = @{

                Path = $env:TEMP + ‘Excel.xlsx’

                Show = $true

                Verbose = $true

            }

            Remove-Item -Path $ExcelParams.Path -Force -EA Ignore

            Write-Output 489 668 299 777 860 151 119 497 234 788 |

                Export-Excel @ExcelParams -ConditionalText $(

                    New-ConditionalText -ConditionalType GreaterThan 525 -ConditionalTextColor DarkRed -BackgroundColor LightPink

                )

 
            Exports data that will have a Conditional Formatting rule in Excel

            that will show cells with a value is greater than 525, whith a

            background fill color of «LightPink» and the text in «DarkRed».

            Where condition is not met the color willbe the default, black

            text on a white background.

 
        .EXAMPLE

        >

        PS> $ExcelParams = @{

                Path = $env:TEMP + ‘Excel.xlsx’

                Show = $true

                Verbose = $true

            }

            Remove-Item -Path $ExcelParams.Path -Force -EA Ignore

            Get-Service | Select-Object -Property Name, Status, DisplayName, ServiceName |

                Export-Excel @ExcelParams -ConditionalText $(

                    New-ConditionalText Stop DarkRed LightPink

                    New-ConditionalText Running Blue Cyan

                )

 
            Exports all services to an Excel sheet, setting a Conditional formatting rule

            that will set the background fill color to «LightPink» and the text color

            to «DarkRed» when the value contains the word «Stop».

            If the value contains the word «Running» it will have a background fill

            color of «Cyan» and text colored ‘Blue’. If neither condition is met, the

            color will be the default, black text on a white background.

 
        .EXAMPLE

        >

        PS> $ExcelParams = @{

                Path = $env:TEMP + ‘Excel.xlsx’

                Show = $true

                Verbose = $true

            }

            Remove-Item -Path $ExcelParams.Path -Force -EA Ignore

 
            $Array = @()

 
            $Obj1 = [PSCustomObject]@{

                Member1 = ‘First’

                Member2 = ‘Second’

            }

 
            $Obj2 = [PSCustomObject]@{

                Member1 = ‘First’

                Member2 = ‘Second’

                Member3 = ‘Third’

            }

 
            $Obj3 = [PSCustomObject]@{

                Member1 = ‘First’

                Member2 = ‘Second’

                Member3 = ‘Third’

                Member4 = ‘Fourth’

            }

 
            $Array = $Obj1, $Obj2, $Obj3

            $Array | Out-GridView -Title ‘Not showing Member3 and Member4’

            $Array | Update-FirstObjectProperties | Export-Excel @ExcelParams -WorksheetName Numbers

 
            Updates the first object of the array by adding property ‘Member3’ and ‘Member4’.

            Afterwards. all objects are exported to an Excel file and all column headers are visible.

 
        .EXAMPLE

            Get-Process | Export-Excel .test.xlsx -WorksheetName Processes -IncludePivotTable -Show -PivotRows Company -PivotData PM

 
        .EXAMPLE

            Get-Process | Export-Excel .test.xlsx -WorksheetName Processes -ChartType PieExploded3D -IncludePivotChart -IncludePivotTable -Show -PivotRows Company -PivotData PM

 
        .EXAMPLE

            Get-Service | Export-Excel ‘c:temptest.xlsx’ -Show -IncludePivotTable -PivotRows status -PivotData @{status=’count’}

 
        .EXAMPLE

        >

        PS> $pt = [ordered]@{}

            $pt.pt1=@{ SourceWorkSheet = ‘Sheet1’;

                       PivotRows = ‘Status’

                       PivotData = @{‘Status’=’count’}

                       IncludePivotChart = $true

                       ChartType = ‘BarClustered3D’

            }

            $pt.pt2=@{ SourceWorkSheet = ‘Sheet2’;

                       PivotRows = ‘Company’

                       PivotData = @{‘Company’=’count’}

                       IncludePivotChart = $true

                       ChartType = ‘PieExploded3D’

            }

            Remove-Item -Path .test.xlsx

            Get-Service | Select-Object -Property Status,Name,DisplayName,StartType | Export-Excel -Path .test.xlsx -AutoSize

            Get-Process | Select-Object -Property Name,Company,Handles,CPU,VM | Export-Excel -Path .test.xlsx -AutoSize -WorksheetName ‘sheet2’

            Export-Excel -Path .test.xlsx -PivotTableDefinition $pt -Show

 
            This example defines two PivotTables. Then it puts Service data on Sheet1

            with one call to Export-Excel and Process Data on sheet2 with a second

            call to Export-Excel. The third and final call adds the two PivotTables

            and opens the spreadsheet in Excel.

        .EXAMPLE

        >

        PS> Remove-Item -Path .test.xlsx

            $excel = Get-Service | Select-Object -Property Status,Name,DisplayName,StartType | Export-Excel -Path .test.xlsx -PassThru

            $excel.Workbook.Worksheets[«Sheet1»].Row(1).style.font.bold = $true

            $excel.Workbook.Worksheets[«Sheet1»].Column(3 ).width = 29

            $excel.Workbook.Worksheets[«Sheet1»].Column(3 ).Style.wraptext = $true

            $excel.Save()

            $excel.Dispose()

            Start-Process .test.xlsx

 
            This example uses -PassThru. It puts service information into sheet1 of the

            workbook and saves the ExcelPackage object in $Excel. It then uses the package

            object to apply formatting, and then saves the workbook and disposes of the object

            before loading the document in Excel. Other commands in the module remove the need

            to work directly with the package object in this way.

 
        .EXAMPLE

        >

        PS> Remove-Item -Path .test.xlsx -ErrorAction Ignore

            $excel = Get-Process | Select-Object -Property Name,Company,Handles,CPU,PM,NPM,WS | Export-Excel -Path .test.xlsx -ClearSheet -WorksheetName «Processes» -PassThru

            $sheet = $excel.Workbook.Worksheets[«Processes»]

            $sheet.Column(1) | Set-ExcelRange -Bold -AutoFit

            $sheet.Column(2) | Set-ExcelRange -Width 29 -WrapText

            $sheet.Column(3) | Set-ExcelRange -HorizontalAlignment Right -NFormat «#,###»

            Set-ExcelRange -Address $sheet.Cells[«E1:H1048576»] -HorizontalAlignment Right -NFormat «#,###»

            Set-ExcelRange -Address $sheet.Column(4) -HorizontalAlignment Right -NFormat «#,##0.0» -Bold

            Set-ExcelRange -Address $sheet.Row(1) -Bold -HorizontalAlignment Center

            Add-ConditionalFormatting -WorkSheet $sheet -Range «D2:D1048576» -DataBarColor Red

            Add-ConditionalFormatting -WorkSheet $sheet -Range «G2:G1048576» -RuleType GreaterThan -ConditionValue «104857600» -ForeGroundColor Red

            foreach ($c in 5..9) {Set-ExcelRange -Address $sheet.Column($c) -AutoFit }

            Export-Excel -ExcelPackage $excel -WorksheetName «Processes» -IncludePivotChart -ChartType ColumnClustered -NoLegend -PivotRows company -PivotData @{‘Name’=’Count’} -Show

 
            This a more sophisticated version of the previous example showing different

            ways of using Set-ExcelRange, and also adding conditional formatting.

            In the final command a PivotChart is added and the workbook is opened in Excel.

        .EXAMPLE

             0..360 | ForEach-Object {[pscustomobject][ordered]@{X=$_; Sinx=»=Sin(Radians(x)) «} } | Export-Excel -now -LineChart -AutoNameRange

 
             Creates a line chart showing the value of Sine(x) for values of X between 0 and 360 degrees.

 
        .EXAMPLE

        >

        PS> Invoke-Sqlcmd -ServerInstance localhostDEFAULT -Database AdventureWorks2014 -Query «select * from sys.tables» -OutputAs DataRows |

            Export-Excel -Path .SysTables_AdventureWorks2014.xlsx -WorksheetName Tables

 
            Runs a query against a SQL Server database and outputs the resulting rows DataRows using the -OutputAs parameter.

            The results are then piped to the Export-Excel function.

            NOTE: You need to install the SqlServer module from the PowerShell Gallery in oder to get the -OutputAs parameter for the Invoke-Sqlcmd cmdlet.

 
        .LINK

            https://github.com/dfinke/ImportExcel

    #>


    [CmdletBinding(DefaultParameterSetName = ‘Default’)]
    [OutputType([OfficeOpenXml.ExcelPackage])]
    [Diagnostics.CodeAnalysis.SuppressMessageAttribute(«PSAvoidUsingPlainTextForPassword», «»)]
    Param(
        [Parameter(ParameterSetName = «Default», Position = 0)]
        [Parameter(ParameterSetName = «Table»  , Position = 0)]
        [String]$Path,
        [Parameter(Mandatory = $true, ParameterSetName = «PackageDefault»)]
        [Parameter(Mandatory = $true, ParameterSetName = «PackageTable»)]
        [OfficeOpenXml.ExcelPackage]$ExcelPackage,
        [Parameter(ValueFromPipeline = $true)]
        [Alias(‘TargetData’)]
        $InputObject,
        [Switch]$Calculate,
        [Switch]$Show,
        [String]$WorksheetName = ‘Sheet1’,
        [String]$Password,
        [switch]$ClearSheet,
        [switch]$Append,
        [String]$Title,
        [OfficeOpenXml.Style.ExcelFillStyle]$TitleFillPattern = ‘Solid’,
        [Switch]$TitleBold,
        [Int]$TitleSize = 22,
        $TitleBackgroundColor,
        [Switch]$IncludePivotTable,
        [String]$PivotTableName,
        [String[]]$PivotRows,
        [String[]]$PivotColumns,
        $PivotData,
        [String[]]$PivotFilter,
        [Switch]$PivotDataToColumn,
        [Hashtable]$PivotTableDefinition,
        [Switch]$IncludePivotChart,
        [OfficeOpenXml.Drawing.Chart.eChartType]$ChartType = ‘Pie’,
        [Switch]$NoLegend,
        [Switch]$ShowCategory,
        [Switch]$ShowPercent,
        [Switch]$AutoSize,
        $MaxAutoSizeRows = 1000,
        [Switch]$NoClobber,
        [Switch]$FreezeTopRow,
        [Switch]$FreezeFirstColumn,
        [Switch]$FreezeTopRowFirstColumn,
        [Int[]]$FreezePane,
        [Parameter(ParameterSetName = ‘Default’)]
        [Parameter(ParameterSetName = ‘PackageDefault’)]
        [Switch]$AutoFilter,
        [Switch]$BoldTopRow,
        [Switch]$NoHeader,
        [ValidateScript( {
                if (-not $_) {  throw ‘RangeName is null or empty.’  }
                elseif ($_[0] -notmatch ‘[a-z]’) { throw ‘RangeName starts with an invalid character.’  }
                else { $true }
            })]
        [String]$RangeName,
        [ValidateScript( {
                if (-not $_) {  throw ‘Tablename is null or empty.’  }
                elseif ($_[0] -notmatch ‘[a-z]’) { throw ‘Tablename starts with an invalid character.’  }
                else { $true }
            })]
        [Parameter(ParameterSetName = ‘Table’        , Mandatory = $true, ValueFromPipelineByPropertyName)]
        [Parameter(ParameterSetName = ‘PackageTable’ , Mandatory = $true, ValueFromPipelineByPropertyName)]
        [String]$TableName,
        [Parameter(ParameterSetName = ‘Table’)]
        [Parameter(ParameterSetName = ‘PackageTable’)]
        [OfficeOpenXml.Table.TableStyles]$TableStyle,
        [Switch]$Barchart,
        [Switch]$PieChart,
        [Switch]$LineChart ,
        [Switch]$ColumnChart ,
        [Object[]]$ExcelChartDefinition,
        [String[]]$HideSheet,
        [String[]]$UnHideSheet,
        [Switch]$MoveToStart,
        [Switch]$MoveToEnd,
        $MoveBefore ,
        $MoveAfter ,
        [Switch]$KillExcel,
        [Switch]$AutoNameRange,
        [Int]$StartRow = 1,
        [Int]$StartColumn = 1,
        [Switch]$PassThru,
        [String]$Numberformat = ‘General’,
        [string[]]$ExcludeProperty,
        [Switch]$NoAliasOrScriptPropeties,
        [Switch]$DisplayPropertySet,
        [String[]]$NoNumberConversion,
        [Object[]]$ConditionalFormat,
        [Object[]]$ConditionalText,
        [ScriptBlock]$CellStyleSB,
        #If there is already content in the workbook the sheet with the PivotTable will not be active UNLESS Activate is specified
        [switch]$Activate,
        [Parameter(ParameterSetName = ‘Now’)]
        [Switch]$Now,
        [Switch]$ReturnRange,
        #By default PivotTables have Totals for each Row (on the right) and for each column at the bottom. This allows just one or neither to be selected.
        [ValidateSet(«Both»,«Columns»,«Rows»,«None»)]
        [String]$PivotTotals = «Both»,
        #Included for compatibility — equivalent to -PivotTotals «None»
        [Switch]$NoTotalsInPivot,
        [Switch]$ReZip
    )

    begin {
        $numberRegex = [Regex]‘d’
        $isDataTypeValueType = $false
        if ($NoClobber) {Write-Warning -Message «-NoClobber parameter is no longer used» }
        #Open the file, get the worksheet, and decide where in the sheet we are writing, and if there is a number format to apply.
        try   {
            $script:Header = $null
            if ($Append -and $ClearSheet) {throw «You can’t use -Append AND -ClearSheet.»}
            if ($PSBoundParameters.Keys.Count -eq 0 -Or $Now -or (-not $Path -and -not $ExcelPackage) ) {
                $Path = [System.IO.Path]::GetTempFileName() -replace ‘.tmp’, ‘.xlsx’
                $Show = $true
                $AutoSize = $true
                if (-not $TableName) {
                    $AutoFilter = $true
                }
            }
            if ($ExcelPackage) {
                $pkg = $ExcelPackage
                $Path = $pkg.File
            }
            Else { $pkg = Open-ExcelPackage -Path $Path -Create -KillExcel:$KillExcel -Password:$Password}
        }
        catch {throw «Could not open Excel Package $path»}
        try   {
            $params = @{WorksheetName=$WorksheetName}
            foreach ($p in @(«ClearSheet», «MoveToStart», «MoveToEnd», «MoveBefore», «MoveAfter», «Activate»)) {if ($PSBoundParameters[$p]) {$params[$p] = $PSBoundParameters[$p]}}
            $ws = $pkg | Add-WorkSheet @params
            if ($ws.Name -ne $WorksheetName) {
                Write-Warning -Message «The Worksheet name has been changed from $WorksheetName to $($ws.Name), this may cause errors later.»
                $WorksheetName = $ws.Name
            }
        }
        catch {throw «Could not get worksheet $worksheetname»}
        try   {
            if ($Append -and $ws.Dimension) {
                #if there is a title or anything else above the header row, append needs to be combined wih a suitable startrow parameter
                $headerRange = $ws.Dimension.Address -replace «d+$», $StartRow
                #using a slightly odd syntax otherwise header ends up as a 2D array
                $ws.Cells[$headerRange].Value | ForEach-Object -Begin {$Script:header = @()} -Process {$Script:header += $_ }
                #if we did not get AutoNameRange, but headers have ranges of the same name make autoNameRange True, otherwise make it false
                if (-not $AutoNameRange) {
                    $AutoNameRange  = $true ; foreach ($h in $header) {if ($ws.names.name -notcontains $h) {$AutoNameRange = $false} }
                }
                #if we did not get a Rangename but there is a Range which covers the active part of the sheet, set Rangename to that.
                if (-not $RangeName -and $ws.names.where({$_.name[0] -match ‘[a-z]’})) {
                    $theRange = $ws.names.where({
                         ($_.Name[0]   -match ‘[a-z]’ )              -and
                         ($_.Start.Row    -eq $StartRow)             -and
                         ($_.Start.Column -eq $StartColumn)          -and
                         ($_.End.Row      -eq $ws.Dimension.End.Row) -and
                         ($_.End.Column   -eq $ws.Dimension.End.column) } , ‘First’, 1)
                    if ($theRange) {$rangename = $theRange.name}
                }

                #if we did not get a table name but there is a table which covers the active part of the sheet, set table name to that, and don’t do anything with autofilter
                if (-not $TableName -and $ws.Tables.Where({$_.address.address -eq $ws.dimension.address})) {
                    $TableName  = $ws.Tables.Where({$_.address.address -eq $ws.dimension.address},‘First’, 1).Name
                    $AutoFilter = $false
                }
                #if we did not get $autofilter but a filter range is set and it covers the right area, set autofilter to true
                elseif (-not $AutoFilter -and $ws.Names[‘_xlnm._FilterDatabase’]) {
                    if ( ($ws.Names[‘_xlnm._FilterDatabase’].Start.Row    -eq $StartRow)    -and
                         ($ws.Names[‘_xlnm._FilterDatabase’].Start.Column -eq $StartColumn) -and
                         ($ws.Names[‘_xlnm._FilterDatabase’].End.Row      -eq $ws.Dimension.End.Row) -and
                         ($ws.Names[‘_xlnm._FilterDatabase’].End.Column   -eq $ws.Dimension.End.Column) ) {$AutoFilter = $true}
                }

                $row = $ws.Dimension.End.Row
                Write-Debug -Message («Appending: headers are « + ($script:Header -join «, «) + » Start row is $row»)
                if ($Title) {Write-Warning -Message «-Title Parameter is ignored when appending.»}
            }
            elseif ($Title) {
                #Can only add a title if not appending!
                $Row = $StartRow
                $ws.Cells[$Row, $StartColumn].Value = $Title
                $ws.Cells[$Row, $StartColumn].Style.Font.Size = $TitleSize

                if  ($PSBoundParameters.ContainsKey(«TitleBold»)) {
                    #Set title to Bold face font if -TitleBold was specified.
                    #Otherwise the default will be unbolded.
                    $ws.Cells[$Row, $StartColumn].Style.Font.Bold = [boolean]$TitleBold
                }
                if ($TitleBackgroundColor ) {
                    if ($TitleBackgroundColor -is [string])         {$TitleBackgroundColor = [System.Drawing.Color]::$TitleBackgroundColor }
                    $ws.Cells[$Row, $StartColumn].Style.Fill.PatternType = $TitleFillPattern
                    $ws.Cells[$Row, $StartColumn].Style.Fill.BackgroundColor.SetColor($TitleBackgroundColor)
                }
                $Row ++ ; $startRow ++
            }
            else {  $Row = $StartRow }
            $ColumnIndex = $StartColumn
            $Numberformat = Expand-NumberFormat -NumberFormat $Numberformat
            if ((-not $ws.Dimension) -and ($Numberformat -ne $ws.Cells.Style.Numberformat.Format)) {
                    $ws.Cells.Style.Numberformat.Format = $Numberformat
                    $setNumformat = $false
            }
            else {  $setNumformat = ($Numberformat -ne $ws.Cells.Style.Numberformat.Format) }
        }
        catch {throw «Failed preparing to export to worksheet ‘$WorksheetName’ to ‘$Path’: $_»}
        #region Special case -inputobject passed a dataTable object
        <# If inputObject was passed via the pipeline it won’t be visible until the process block, we will only see it here if it was passed as a parameter

          if it was passed it is a data table don’t do foreach on it (slow) put the whole table in and set dates on date columns,

          set things up for the end block, and skip the process block #>

        if ($InputObject -is  [System.Data.DataTable])  {
            $null = $ws.Cells[$row,$StartColumn].LoadFromDataTable($InputObject, (-not $noHeader) )
            foreach ($c in $InputObject.Columns.where({$_.datatype -eq [datetime]})) {
                Set-ExcelColumn -Worksheet $ws -Column ($c.Ordinal + $StartColumn) -NumberFormat ‘Date-Time’
            }
            foreach ($c in $InputObject.Columns.where({$_.datatype -eq [timespan]})) {
                Set-ExcelColumn -Worksheet $ws -Column ($c.Ordinal + $StartColumn) -NumberFormat ‘[h]:mm:ss’
            }
            $ColumnIndex         += $InputObject.Columns.Count  1
            if ($noHeader) {$row += $InputObject.Rows.Count 1 }
            else           {$row += $InputObject.Rows.Count    }
            $null = $PSBoundParameters.Remove(‘InputObject’)
            $firstTimeThru = $false
        }
        #endregion
        else  {$firstTimeThru = $true}
    }

    process { if ($PSBoundParameters.ContainsKey(«InputObject»)) {
        try {
            if ($null -eq $InputObject) {$row += 1}
            foreach ($TargetData in $InputObject) {
                if ($firstTimeThru) {
                    $firstTimeThru = $false
                    $isDataTypeValueType = ($null -eq $TargetData) -or ($TargetData.GetType().name -match ‘string|timespan|datetime|bool|byte|char|decimal|double|float|int|long|sbyte|short|uint|ulong|ushort|URI|ExcelHyperLink’)
                    if ($isDataTypeValueType ) {
                        $script:Header = @(«.»)       # dummy value to make sure we go through the «for each name in $header»
                        if (-not $Append) {$row -= 1} # By default row will be 1, it is incremented before inserting values (so it ends pointing at final row.); si first data row is 2 — move back up 1 if there is no header .
                    }
                    if ($null -ne $TargetData) {Write-Debug «DataTypeName is ‘$($TargetData.GetType().name)’ isDataTypeValueType ‘$isDataTypeValueType'» }
                }
                #region Add headers — if we are appending, or we have been through here once already we will have the headers
                if (-not $script:Header) {
                    if ($DisplayPropertySet -and $TargetData.psStandardmembers.DefaultDisplayPropertySet.ReferencedPropertyNames) {
                        $script:Header = $TargetData.psStandardmembers.DefaultDisplayPropertySet.ReferencedPropertyNames.Where( {$_ -notin $ExcludeProperty})
                    }
                    else {
                        if ($NoAliasOrScriptPropeties) {$propType = «Property»} else {$propType = «*»}
                        $script:Header = $TargetData.PSObject.Properties.where( {$_.MemberType -like $propType}).Name
                    }
                    foreach ($exclusion in $ExcludeProperty) {$script:Header = $script:Header -notlike $exclusion}
                    if ($NoHeader) {
                        # Don’t push the headers to the spreadsheet
                        $Row -= 1
                    }
                    else {
                        $ColumnIndex = $StartColumn
                        foreach ($Name in $script:Header) {
                            $ws.Cells[$Row, $ColumnIndex].Value = $Name
                            Write-Verbose «Cell ‘$Row`:$ColumnIndex’ add header ‘$Name'»
                            $ColumnIndex += 1
                        }
                    }
                }
                #endregion
                #region Add non header values
                $Row += 1
                $ColumnIndex = $StartColumn
                <#

                 For each item in the header OR for the Data item if this is a simple Type or data table :

                   If it is a date insert with one of Excel’s built in formats — recognized as «Date and time to be localized»

                   if it is a timespan insert with a built in format for elapsed hours, minutes and seconds

                   if its any other numeric insert as is , setting format if need be.

                   Preserve URI, Insert a data table, convert non string objects to string.

                   For strings, check for fomula, URI or Number, before inserting as a string (ignore nulls) #>

                foreach ($Name in $script:Header) {
                    if   ($isDataTypeValueType) {$v = $TargetData}
                    else {$v = $TargetData.$Name}
                    try   {
                        if     ($v -is    [DateTime]) {
                            $ws.Cells[$Row, $ColumnIndex].Value = $v
                            $ws.Cells[$Row, $ColumnIndex].Style.Numberformat.Format = ‘m/d/yy h:mm’ # This is not a custom format, but a preset recognized as date and localized.
                        }
                        elseif ($v -is    [TimeSpan]) {
                            $ws.Cells[$Row, $ColumnIndex].Value = $v
                            $ws.Cells[$Row, $ColumnIndex].Style.Numberformat.Format = ‘[h]:mm:ss’
                        }
                        elseif ($v -is    [System.ValueType]) {
                            $ws.Cells[$Row, $ColumnIndex].Value = $v
                            if ($setNumformat) {$ws.Cells[$Row, $ColumnIndex].Style.Numberformat.Format = $Numberformat }
                        }
                        elseif ($v -is    [uri] ) {
                            $ws.Cells[$Row, $ColumnIndex].HyperLink = $v
                            $ws.Cells[$Row, $ColumnIndex].Style.Font.Color.SetColor([System.Drawing.Color]::Blue)
                            $ws.Cells[$Row, $ColumnIndex].Style.Font.UnderLine = $true
                        }
                        elseif ($v -isnot [String] ) { #Other objects or null.
                            if ($null -ne $v) { $ws.Cells[$Row, $ColumnIndex].Value = $v.toString()}
                        }
                        elseif ($v[0] -eq ‘=’) {
                            $ws.Cells[$Row, $ColumnIndex].Formula = ($v -replace ‘^=’,»)
                            if ($setNumformat) {$ws.Cells[$Row, $ColumnIndex].Style.Numberformat.Format = $Numberformat }
                        }
                        elseif ( [System.Uri]::IsWellFormedUriString($v , [System.UriKind]::Absolute) ) {
                            if ($v -match «^xl://internal/») {
                                  $referenceAddress = $v -replace «^xl://internal/» , «»
                                  $display          = $referenceAddress -replace «!A1$»   , «»
                                  $h = New-Object -TypeName OfficeOpenXml.ExcelHyperLink -ArgumentList $referenceAddress , $display
                                  $ws.Cells[$Row, $ColumnIndex].HyperLink = $h
                            }
                            else {$ws.Cells[$Row, $ColumnIndex].HyperLink = $v }   #$ws.Cells[$Row, $ColumnIndex].Value = $v.AbsoluteUri
                            $ws.Cells[$Row, $ColumnIndex].Style.Font.Color.SetColor([System.Drawing.Color]::Blue)
                            $ws.Cells[$Row, $ColumnIndex].Style.Font.UnderLine = $true
                        }
                        else {
                            $number = $null
                            if ( $numberRegex.IsMatch($v)     -and  # if it contains digit(s) — this syntax is quicker than -match for many items and cuts out slow checks for non numbers
                                 $NoNumberConversion -ne ‘*’  -and  # and NoNumberConversion isn’t specified
                                 $NoNumberConversion -notcontains $Name -and
                                 [Double]::TryParse($v, [System.Globalization.NumberStyles]::Any, [System.Globalization.NumberFormatInfo]::CurrentInfo, [Ref]$number)
                               ) {
                                 $ws.Cells[$Row, $ColumnIndex].Value = $number
                                 if ($setNumformat) {$ws.Cells[$Row, $ColumnIndex].Style.Numberformat.Format = $Numberformat }
                            }
                            else {
                                $ws.Cells[$Row, $ColumnIndex].Value  = $v
                            }

                        }
                    }
                    catch {Write-Warning -Message «Could not insert the ‘$Name’ property at Row $Row, Column $ColumnIndex»}
                    $ColumnIndex += 1
                }
                $ColumnIndex -= 1 # column index will be the last column whether isDataTypeValueType was true or false
                #endregion
            }
        }
        catch {throw «Failed exporting data to worksheet ‘$WorksheetName’ to ‘$Path’: $_» }

    }}

    end {
        if ($firstTimeThru -and $ws.Dimension) {
              $LastRow        = $ws.Dimension.End.Row
              $LastCol        = $ws.Dimension.End.Column
              $endAddress     = $ws.Dimension.End.Address
        }
        else {
              $LastRow        = $Row
              $LastCol        = $ColumnIndex
              $endAddress     = [OfficeOpenXml.ExcelAddress]::GetAddress($LastRow , $LastCol)
        }
        $startAddress         = [OfficeOpenXml.ExcelAddress]::GetAddress($StartRow, $StartColumn)
        $dataRange            = «{0}:{1}» -f $startAddress, $endAddress

        Write-Debug «Data Range ‘$dataRange'»
        if ($AutoNameRange) {
            try {
                if (-not $script:header) {
                    # if there aren’t any headers, use the the first row of data to name the ranges: this is the last point that headers will be used.
                    $headerRange = $ws.Dimension.Address -replace «d+$», $StartRow
                    #using a slightly odd syntax otherwise header ends up as a 2D array
                    $ws.Cells[$headerRange].Value | ForEach-Object -Begin {$Script:header = @()} -Process {$Script:header += $_ }
                    if   ($PSBoundParameters.ContainsKey($TargetData)) {  #if Export was called with data that writes no header start the range at $startRow ($startRow is data)
                           $targetRow = $StartRow
                    }
                    else { $targetRow = $StartRow + 1 }                   #if Export was called without data to add names (assume $startRow is a header) or…
                }                                                         # … called with data that writes a header, then start the range at $startRow + 1
                else {     $targetRow = $StartRow + 1 }

                #Dimension.start.row always seems to be one so we work out the target row
                #, but start.column is the first populated one and .Columns is the count of populated ones.
                # if we have 5 columns from 3 to 8, headers are numbered 0..4, so that is in the for loop and used for getting the name…
                # but we have to add the start column on when referencing positions
                foreach ($c in 0..($LastCol  $StartColumn)) {
                    $targetRangeName = @($script:Header)[$c]  #Let Add-ExcelName fix (and warn about) bad names
                    Add-ExcelName  -RangeName $targetRangeName -Range $ws.Cells[$targetRow, ($StartColumn + $c ), $LastRow, ($StartColumn + $c )]
                    try {#this test can throw with some names, surpress any error
                        if ([OfficeOpenXml.FormulaParsing.ExcelUtilities.ExcelAddressUtil]::IsValidAddress(($targetRangeName -replace ‘W’ , ‘_’ ))) {
                            Write-Warning «AutoNameRange: Property name ‘$targetRangeName’ is also a valid Excel address and may cause issues. Consider renaming the property name.»
                        }
                    } Catch {}
                }
            }
            catch {Write-Warning -Message «Failed adding named ranges to worksheet ‘$WorksheetName’: $_»  }
        }
        #Empty string is not allowed as a name for ranges or tables.
        if ($RangeName) { Add-ExcelName  -Range $ws.Cells[$dataRange] -RangeName $RangeName}

        if ($TableName) {
            if ($PSBoundParameters.ContainsKey(‘TableStyle’)) {
                  Add-ExcelTable -Range $ws.Cells[$dataRange] -TableName $TableName -TableStyle $TableStyle
            }
            else {Add-ExcelTable -Range $ws.Cells[$dataRange] -TableName $TableName}
        }

        if ($AutoFilter) {
            try {
                $ws.Cells[$dataRange].AutoFilter = $true
                Write-Verbose -Message «Enabled autofilter. «
            }
            catch {Write-Warning -Message «Failed adding autofilter to worksheet ‘$WorksheetName’: $_»}
        }

        if ($PivotTableDefinition) {
            foreach ($item in $PivotTableDefinition.GetEnumerator()) {
                $params = $item.value
                if ($Activate) {$params.Activate = $true   }
                if ($params.keys -notcontains ‘SourceRange’ -and
                   ($params.Keys -notcontains ‘SourceWorkSheet’   -or  $params.SourceWorkSheet -eq $WorksheetName)) {$params.SourceRange = $dataRange}
                if ($params.Keys -notcontains ‘SourceWorkSheet’)      {$params.SourceWorkSheet = $ws }
                if ($params.Keys -notcontains ‘NoTotalsInPivot’   -and $NoTotalsInPivot  ) {$params.PivotTotals       = ‘None’}
                if ($params.Keys -notcontains ‘PivotTotals’       -and $PivotTotals      ) {$params.PivotTotals       = $PivotTotals}
                if ($params.Keys -notcontains ‘PivotDataToColumn’ -and $PivotDataToColumn) {$params.PivotDataToColumn = $true}

                Add-PivotTable -ExcelPackage $pkg -PivotTableName $item.key @Params
            }
        }
        if ($IncludePivotTable -or $IncludePivotChart) {
            $params = @{
                ‘SourceRange’ = $dataRange
            }
            if ($PivotTableName -and ($pkg.workbook.worksheets.tables.name -contains $PivotTableName)) {
                Write-Warning -Message «The selected PivotTable name ‘$PivotTableName’ is already used as a table name. Adding a suffix of ‘Pivot’.»
                $PivotTableName += ‘Pivot’
            }

            if   ($PivotTableName)  {$params.PivotTableName    = $PivotTableName}
            else                    {$params.PivotTableName    = $WorksheetName + ‘PivotTable’}
            if          ($Activate) {$params.Activate          = $true   }
            if       ($PivotFilter) {$params.PivotFilter       = $PivotFilter}
            if         ($PivotRows) {$params.PivotRows         = $PivotRows}
            if      ($PivotColumns) {$Params.PivotColumns      = $PivotColumns}
            if         ($PivotData) {$Params.PivotData         = $PivotData}
            if   ($NoTotalsInPivot) {$params.PivotTotals       = «None»    }
            Elseif   ($PivotTotals) {$params.PivotTotals       = $PivotTotals}
            if ($PivotDataToColumn) {$params.PivotDataToColumn = $true}
            if ($IncludePivotChart) {
                                     $params.IncludePivotChart = $true
                                     $Params.ChartType         = $ChartType
                if ($ShowCategory)  {$params.ShowCategory      = $true}
                if ($ShowPercent)   {$params.ShowPercent       = $true}
                if ($NoLegend)      {$params.NoLegend          = $true}
            }
            Add-PivotTable -ExcelPackage $pkg -SourceWorkSheet $ws   @params
        }

        try {
            #Allow single switch or two seperate ones.
            if ($FreezeTopRowFirstColumn -or ($FreezeTopRow -and $FreezeFirstColumn)) {
                $ws.View.FreezePanes(2, 2)
                Write-Verbose -Message «Froze top row and first column»
            }
            elseif ($FreezeTopRow) {
                $ws.View.FreezePanes(2, 1)
                Write-Verbose -Message «Froze top row»
            }
            elseif ($FreezeFirstColumn) {
                $ws.View.FreezePanes(1, 2)
                Write-Verbose -Message «Froze first column»
            }
            #Must be 1..maxrows or and array of 1..maxRows,1..MaxCols
            if ($FreezePane) {
                $freezeRow, $freezeColumn = $FreezePane
                if (-not $freezeColumn -or $freezeColumn -eq 0) {
                    $freezeColumn = 1
                }

                if ($freezeRow -ge 1) {
                    $ws.View.FreezePanes($freezeRow, $freezeColumn)
                    Write-Verbose -Message «Froze panes at row $freezeRow and column $FreezeColumn»
                }
            }
        }
        catch {Write-Warning -Message «Failed adding Freezing the panes in worksheet ‘$WorksheetName’: $_»}

        if  ($PSBoundParameters.ContainsKey(«BoldTopRow»)) { #it sets bold as far as there are populated cells: for whole row could do $ws.row($x).style.font.bold = $true
            try {
                if ($Title) {
                    $range = $ws.Dimension.Address -replace ‘d+’, ($StartRow + 1)
                }
                else {
                    $range = $ws.Dimension.Address -replace ‘d+’, $StartRow
                }
                $ws.Cells[$range].Style.Font.Bold = [boolean]$BoldTopRow
                Write-Verbose -Message «Set $range font style to bold.»
            }
            catch {Write-Warning -Message «Failed setting the top row to bold in worksheet ‘$WorksheetName’: $_»}
        }
        if ($AutoSize) {
            try {
                #Don’t fit the all the columns in the sheet; if we are adding cells beside things with hidden columns, that unhides them
                if ($MaxAutoSizeRows -and $MaxAutoSizeRows -lt $LastRow ) {
                    $AutosizeRange = [OfficeOpenXml.ExcelAddress]::GetAddress($startRow,$StartColumn,   $MaxAutoSizeRows , $LastCol)
                    $ws.Cells[$AutosizeRange].AutoFitColumns()
                }
                else {$ws.Cells[$dataRange].AutoFitColumns()  }
                Write-Verbose -Message «Auto-sized columns»
            }
            catch {  Write-Warning -Message «Failed autosizing columns of worksheet ‘$WorksheetName’: $_»}
        }

        foreach ($Sheet in $HideSheet) {
            try {
                $pkg.Workbook.WorkSheets.Where({$_.Name -like $sheet}) | ForEach-Object {
                    $_.Hidden = ‘Hidden’
                    Write-verbose -Message «Sheet ‘$($_.Name)’ Hidden.»
                }
            }
            catch {Write-Warning -Message  «Failed hiding worksheet ‘$sheet’: $_»}
        }
        foreach ($Sheet in $UnHideSheet) {
            try {
                $pkg.Workbook.WorkSheets.Where({$_.Name -like $sheet}) | ForEach-Object {
                    $_.Hidden = ‘Visible’
                    Write-verbose -Message «Sheet ‘$($_.Name)’ shown»
                }
            }
            catch {Write-Warning -Message  «Failed showing worksheet ‘$sheet’: $_»}
        }
        if (-not $pkg.Workbook.Worksheets.Where({$_.Hidden -eq ‘visible’})) {
            Write-Verbose -Message «No Sheets were left visible, making $WorksheetName visible»
            $ws.Hidden = ‘Visible’
        }

        foreach ($chartDef in $ExcelChartDefinition) {
            if ($chartDef -is [System.Management.Automation.PSCustomObject]) {
                $params = @{}
                $chartDef.PSObject.Properties | ForEach-Object {if ( $null -ne $_.value) {$params[$_.name] = $_.value}}
                Add-ExcelChart -Worksheet $ws @params
            }
            elseif ($chartDef -is [hashtable] -or  $chartDef -is[System.Collections.Specialized.OrderedDictionary]) {
                Add-ExcelChart -Worksheet $ws @chartDef
            }
        }

        if ($Calculate) {
            try   { [OfficeOpenXml.CalculationExtension]::Calculate($ws) }
            catch { Write-Warning «One or more errors occured while calculating, save will continue, but there may be errors in the workbook. $_»}
        }

        if ($Barchart -or $PieChart -or $LineChart -or $ColumnChart) {
            if ($NoHeader) {$FirstDataRow = $startRow}
            else           {$FirstDataRow = $startRow + 1 }
            $range = [OfficeOpenXml.ExcelAddress]::GetAddress($FirstDataRow, $startColumn, $FirstDataRow, $lastCol )
            $xCol  = $ws.cells[$range] | Where-Object {$_.value -is [string]    } | ForEach-Object {$_.start.column} | Sort-Object | Select-Object -first 1
            if (-not $xcol) {
                $xcol  = $StartColumn
                $range = [OfficeOpenXml.ExcelAddress]::GetAddress($FirstDataRow, ($startColumn +1), $FirstDataRow, $lastCol )
            }
            $yCol  = $ws.cells[$range] | Where-Object {$_.value -is [valueType] -or $_.Formula } | ForEach-Object {$_.start.column} | Sort-Object | Select-Object -first 1
            if (-not ($xCol -and $ycol)) { Write-Warning -Message «Can’t identify a string column and a number column to use as chart labels and data. «}
            else {
                $params = @{
                XRange = [OfficeOpenXml.ExcelAddress]::GetAddress($FirstDataRow, $xcol , $lastrow, $xcol)
                YRange = [OfficeOpenXml.ExcelAddress]::GetAddress($FirstDataRow, $ycol , $lastrow, $ycol)
                Title  =  »
                Column = ($lastCol +1)
                Width  = 800
                }
                if   ($ShowPercent) {$params[«ShowPercent»]  = $true}
                if  ($ShowCategory) {$params[«ShowCategory»] = $true}
                if      ($NoLegend) {$params[«NoLegend»]     = $true}
                if (-not $NoHeader) {$params[«SeriesHeader»] = $ws.Cells[$startRow, $YCol].Value}
                if   ($ColumnChart) {$Params[«chartType»]    = «ColumnStacked» }
                elseif  ($Barchart) {$Params[«chartType»]    = «BarStacked»    }
                elseif  ($PieChart) {$Params[«chartType»]    = «PieExploded3D» }
                elseif ($LineChart) {$Params[«chartType»]    = «Line»          }

                Add-ExcelChart -Worksheet $ws @params
            }
        }

        # It now doesn’t matter if the conditional formating rules are passed in $conditionalText or $conditional format.
        # Just one with an alias for compatiblity it will break things for people who are using both at once
        foreach ($c in  (@() + $ConditionalText  +  $ConditionalFormat) ) {
            try {
                #we can take an object with a .ConditionalType property made by New-ConditionalText or with a .Formatter Property made by New-ConditionalFormattingIconSet or a hash table
                if ($c.ConditionalType) {
                    $cfParams = @{RuleType = $c.ConditionalType;    ConditionValue = $c.Text ;
                           BackgroundColor = $c.BackgroundColor; BackgroundPattern = $c.PatternType  ;
                           ForeGroundColor = $c.ConditionalTextColor}
                    if ($c.Range) {$cfParams.Range = $c.Range}
                    else          {$cfParams.Range = $ws.Dimension.Address }
                    Add-ConditionalFormatting -WorkSheet $ws @cfParams
                    Write-Verbose -Message «Added conditional formatting to range $($c.range)»
                }
                elseif ($c.formatter)  {
                    switch ($c.formatter) {
                        «ThreeIconSet» {Add-ConditionalFormatting -WorkSheet $ws -ThreeIconsSet $c.IconType -range $c.range -reverse:$c.reverse  }
                        «FourIconSet»  {Add-ConditionalFormatting -WorkSheet $ws  -FourIconsSet $c.IconType -range $c.range -reverse:$c.reverse  }
                        «FiveIconSet»  {Add-ConditionalFormatting -WorkSheet $ws  -FiveIconsSet $c.IconType -range $c.range -reverse:$c.reverse  }
                    }
                    Write-Verbose -Message «Added conditional formatting to range $($c.range)»
                }
                elseif ($c -is [hashtable] -or  $c -is[System.Collections.Specialized.OrderedDictionary]) {
                    if (-not $c.Range -or $c.Address) {$c.Address = $ws.Dimension.Address }
                    Add-ConditionalFormatting -WorkSheet $ws @c
                }
            }
            catch {throw «Error applying conditional formatting to worksheet $_»}
        }

        if ($CellStyleSB) {
            try {
                $TotalRows = $ws.Dimension.Rows
                $LastColumn = $ws.Dimension.Address -replace «^.*:(w*)d+$» , ‘$1’
                & $CellStyleSB $ws $TotalRows $LastColumn
            }
            catch {Write-Warning -Message «Failed processing CellStyleSB in worksheet ‘$WorksheetName’: $_»}
        }

        #Can only add password, may want to support -password $Null removing password.
        if ($Password) {
            try {
                $ws.Protection.SetPassword($Password)
                Write-Verbose -Message ‘Set password on workbook’
            }

            catch {throw «Failed setting password for worksheet ‘$WorksheetName’: $_»}
        }

        if ($PassThru) {       $pkg   }
        else {
            if ($ReturnRange) {$dataRange }

            if ($Password) { $pkg.Save($Password) }
            else           { $pkg.Save() }
            Write-Verbose -Message «Saved workbook $($pkg.File)»
            if ($ReZip) {
                Write-Verbose -Message «Re-Zipping $($pkg.file) using .NET ZIP library»
                try {
                    Add-Type -AssemblyName ‘System.IO.Compression.Filesystem’ -ErrorAction stop
                }
                catch {
                    Write-Error «The -ReZip parameter requires .NET Framework 4.5 or later to be installed. Recommend to install Powershell v4+»
                    continue
                }
                try {
                    $TempZipPath = Join-Path -Path ([System.IO.Path]::GetTempPath()) -ChildPath ([System.IO.Path]::GetRandomFileName())
                    $null = [io.compression.zipfile]::ExtractToDirectory($pkg.File, $TempZipPath)
                    Remove-Item $pkg.File -Force
                    $null = [io.compression.zipfile]::CreateFromDirectory($TempZipPath, $pkg.File)
                }
                catch {throw «Error resizipping $path : $_»}
            }

            $pkg.Dispose()

            if ($Show) { Invoke-Item $Path }
        }

    }
}

function Add-WorkSheet  {
    <#

      .Synopsis

        Adds a worksheet to an existing workbook.

      .Description

        If the named worksheet already exists, the -Clearsheet parameter decides whether it should be deleted and a new one returned,

        or if not specified the existing sheet will be returned. By default the sheet is created at the end of the work book, the

        -MoveXXXX switches allow the sheet to be [re]positioned at the start or before or after another sheet. A new sheet will only be

        made the default sheet when excel opens if -Activate is specified.

      .Example

        $WorksheetActors = $ExcelPackage | Add-WorkSheet -WorkSheetname Actors

 
        $ExcelPackage holds an Excel package object (returned by Open-ExcelPackage, or Export-Excel -passthru).

        This command will add a sheet named ‘Actors’, or return the sheet if it exists, and the result is stored in $WorkSheetActors.

      .Example

        $WorksheetActors = Add-WorkSheet -ExcelPackage $ExcelPackage -WorkSheetname «Actors» -ClearSheet -MoveToStart

 
        This time the Excel package object is passed as a parameter instead of piped. If the ‘Actors’ sheet already exists it is deleted

        and re-created. The new sheet will be created last in the workbook, and -MoveToStart Moves it to the start.

      .Example

        $null = Add-WorkSheet -ExcelWorkbook $wb -WorkSheetname $DestinationName -CopySource $sourceWs -Activate

        This time a workbook is used instead of a package, and a worksheet is copied — $SourceWs is a worksheet object, which can come

        from the same workbook or a different one. Here the new copy of the data is made the active sheet when the workbook is opened.

    #>


    [cmdletBinding()]
    [OutputType([OfficeOpenXml.ExcelWorksheet])]
    param(
        #An object representing an Excel Package.
        [Parameter(Mandatory = $true, ValueFromPipeline = $true, ParameterSetName = «Package», Position = 0)]
        [OfficeOpenXml.ExcelPackage]$ExcelPackage,
        #An Excel Workbook to which the Worksheet will be added — a Package contains one Workbook, so you can use whichever fits at the time.
        [Parameter(Mandatory = $true, ParameterSetName = «WorkBook»)]
        [OfficeOpenXml.ExcelWorkbook]$ExcelWorkbook,
        #The name of the worksheet, ‘Sheet1’ by default.
        [string]$WorksheetName ,
        #If the worksheet already exists, by default it will returned, unless -ClearSheet is specified in which case it will be deleted and re-created.
        [switch]$ClearSheet,
        #If specified, the worksheet will be moved to the start of the workbook.
        #MoveToStart takes precedence over MoveToEnd, Movebefore and MoveAfter if more than one is specified.
        [Switch]$MoveToStart,
        #If specified, the worksheet will be moved to the end of the workbook.
        #(This is the default position for newly created sheets, but this can be used to move existing sheets.)
        [Switch]$MoveToEnd,
        #If specified, the worksheet will be moved before the nominated one (which can be an index starting from 1, or a name).
        #MoveBefore takes precedence over MoveAfter if both are specified.
        $MoveBefore ,
        # If specified, the worksheet will be moved after the nominated one (which can be an index starting from 1, or a name or *).
        # If * is used, the worksheet names will be examined starting with the first one, and the sheet placed after the last sheet which comes before it alphabetically.
        $MoveAfter ,
        #If there is already content in the workbook the new sheet will not be active UNLESS Activate is specified.
        [switch]$Activate,
        #If worksheet is provided as a copy source the new worksheet will be a copy of it. The source can be in the same workbook, or in a different file.
        [OfficeOpenXml.ExcelWorksheet]$CopySource,
        #Ignored but retained for backwards compatibility.
        [Switch] $NoClobber
    )
    #if we were given a workbook use it, if we were given a package, use its workbook
    if      ($ExcelPackage -and -not $ExcelWorkbook) {$ExcelWorkbook = $ExcelPackage.Workbook}

    # If WorksheetName was given, try to use that worksheet. If it wasn’t, and we are copying an existing sheet, try to use the sheet name
    # If we are not copying a sheet, and have no name, use the name «SheetX» where X is the number of the new sheet
    if      (-not $WorksheetName -and $CopySource -and -not $ExcelWorkbook[$CopySource.Name]) {$WorksheetName = $CopySource.Name}
    elseif  (-not $WorksheetName) {$WorksheetName = «Sheet» + (1 + $ExcelWorkbook.Worksheets.Count)}
    else    {$ws = $ExcelWorkbook.Worksheets[$WorksheetName]}

    #If -clearsheet was specified and the named sheet exists, delete it
    if      ($ws -and $ClearSheet) { $ExcelWorkbook.Worksheets.Delete($WorksheetName) ; $ws = $null }

    #Copy or create new sheet as needed
    if (-not $ws -and $CopySource) {
          Write-Verbose -Message «Copying into worksheet ‘$WorksheetName’.»
          $ws = $ExcelWorkbook.Worksheets.Add($WorksheetName, $CopySource)
    }
    elseif (-not $ws) {
          $ws = $ExcelWorkbook.Worksheets.Add($WorksheetName)
          Write-Verbose -Message «Adding worksheet ‘$WorksheetName’.»
    }
    else {Write-Verbose -Message «Worksheet ‘$WorksheetName’ already existed.»}
    #region Move sheet if needed
    if     ($MoveToStart) {$ExcelWorkbook.Worksheets.MoveToStart($WorksheetName) }
    elseif ($MoveToEnd  ) {$ExcelWorkbook.Worksheets.MoveToEnd($WorksheetName)   }
    elseif ($MoveBefore ) {
        if ($ExcelWorkbook.Worksheets[$MoveBefore]) {
            if ($MoveBefore -is [int]) {
                $ExcelWorkbook.Worksheets.MoveBefore($ws.Index, $MoveBefore)
            }
            else {$ExcelWorkbook.Worksheets.MoveBefore($WorksheetName, $MoveBefore)}
        }
        else {Write-Warning «Can’t find worksheet ‘$MoveBefore’; worsheet ‘$WorksheetName’ will not be moved.»}
    }
    elseif ($MoveAfter  ) {
        if ($MoveAfter -eq «*») {
            if ($WorksheetName -lt $ExcelWorkbook.Worksheets[1].Name) {$ExcelWorkbook.Worksheets.MoveToStart($WorksheetName)}
            else {
                $i = 1
                While ($i -lt $ExcelWorkbook.Worksheets.Count -and ($ExcelWorkbook.Worksheets[$i + 1].Name -le $WorksheetName) ) { $i++}
                $ExcelWorkbook.Worksheets.MoveAfter($ws.Index, $i)
            }
        }
        elseif ($ExcelWorkbook.Worksheets[$MoveAfter]) {
            if ($MoveAfter -is [int]) {
                $ExcelWorkbook.Worksheets.MoveAfter($ws.Index, $MoveAfter)
            }
            else {
                $ExcelWorkbook.Worksheets.MoveAfter($WorksheetName, $MoveAfter)
            }
        }
        else {Write-Warning «Can’t find worksheet ‘$MoveAfter’; worsheet ‘$WorksheetName’ will not be moved.»}
    }
    #endregion
    if ($Activate) {Select-Worksheet -ExcelWorksheet $ws  }
    if ($ExcelPackage -and -not (Get-Member -InputObject $ExcelPackage -Name $ws.Name)) {
        $sb = [scriptblock]::Create((‘$this.workbook.Worksheets[«{0}»]’ -f $ws.name))
        Add-Member -InputObject $ExcelPackage -MemberType ScriptProperty -Name $ws.name -Value $sb
    }
    return $ws
}

function Select-Worksheet {
   <#

      .SYNOPSIS

        Sets the selected tab in an Excel workbook to be the chosen sheet and unselects all the others.

      .DESCRIPTION

        Sometimes when a sheet is added we want it to be the active sheet, sometimes we want the active sheet to be left as it was.

        Select-Worksheet exists to change which sheet is the selected tab when Excel opens the file.

      .EXAMPLE

        Select-Worksheet -ExcelWorkbook $ExcelWorkbook -WorksheetName «NewSheet»

        $ExcelWorkbook holds a workbook object containing a sheet named «NewSheet»;

        This sheet will become the [only] active sheet in the workbook

      .EXAMPLE

        Select-Worksheet -ExcelPackage $Pkg -WorksheetName «NewSheet2»

        $pkg holds an Excel Package, whose workbook contains a sheet named «NewSheet2»

        This sheet will become the [only] active sheet in the workbook.

      .EXAMPLE

        Select-Worksheet -ExcelWorksheet $ws

        $ws holds an Excel worksheet which will become the [only] active sheet

        in its workbook.

    #>

    param (
        #An object representing an ExcelPackage.
        [Parameter(Mandatory = $true, ValueFromPipeline = $true, ParameterSetName = ‘Package’, Position = 0)]
        [OfficeOpenXml.ExcelPackage]$ExcelPackage,
        #An Excel workbook to which the Worksheet will be added — a package contains one Workbook so you can use workbook or package as it suits.
        [Parameter(Mandatory = $true, ParameterSetName = ‘WorkBook’)]
        [OfficeOpenXml.ExcelWorkbook]$ExcelWorkbook,
        [Parameter(ParameterSetName=‘Package’)]
        [Parameter(ParameterSetName=‘Workbook’)]
        #The name of the worksheet «Sheet1» by default.
        [string]$WorksheetName,
        #An object representing an Excel worksheet.
        [Parameter(ParameterSetName=‘Sheet’,Mandatory=$true)]
        [OfficeOpenXml.ExcelWorksheet]$ExcelWorksheet
    )
    #if we were given a package, use its workbook
    if      ($ExcelPackage   -and -not $ExcelWorkbook) {$ExcelWorkbook  = $ExcelPackage.Workbook}
    #if we now have workbook, get the worksheet; if we were given a sheet get the workbook
    if      ($ExcelWorkbook  -and $WorksheetName)      {$ExcelWorksheet = $ExcelWorkbook.Worksheets[$WorksheetName]}
    elseif  ($ExcelWorksheet -and -not $ExcelWorkbook) {$ExcelWorkbook  = $ExcelWorksheet.Workbook ; }
    #if we didn’t get to a worksheet give up. If we did set all works sheets to not selected and then the one we want to selected.
    if (-not $ExcelWorksheet) {Write-Warning -Message «The worksheet $WorksheetName was not found.» ; return }
    else {
        foreach ($w in $ExcelWorkbook.Worksheets) {$w.View.TabSelected = $false}
        $ExcelWorksheet.View.TabSelected = $true
    }
}

Function Add-ExcelName {
    <#

      .SYNOPSIS

        Adds a named-range to an existing Excel worksheet.

      .DESCRIPTION

        It is often helpful to be able to refer to sets of cells with a name rather than using their co-ordinates; Add-ExcelName sets up these names.

      .EXAMPLE

          Add-ExcelName -Range $ws.Cells[$dataRange] -RangeName $rangeName

          $WS is a worksheet, and $dataRange is a string describing a range of cells — e.g. «A1:Z10»

          which will become a named range, using the name in $rangeName.

    #>

    [CmdletBinding()]
    param(
        #The range of cells to assign as a name.
        [Parameter(Mandatory=$true)]
        [OfficeOpenXml.ExcelRange]$Range,
        #The name to assign to the range. If the name exists it will be updated to the new range. If no name is specified, the first cell in the range will be used as the name.
        [String]$RangeName
    )
    try {
        $ws = $Range.Worksheet
        if (-not $RangeName) {
            $RangeName = $ws.Cells[$Range.Start.Address].Value
            $Range  = ($Range.Worksheet.cells[($range.start.row +1), $range.start.Column ,  $range.end.row, $range.end.column])
        }
        if ($RangeName -match ‘W’) {
            Write-Warning -Message «Range name ‘$RangeName’ contains illegal characters, they will be replaced with ‘_’.»
            $RangeName = $RangeName -replace ‘W’,‘_’
        }
        if ($ws.names[$RangeName]) {
            Write-verbose -Message «Updating Named range ‘$RangeName’ to $($Range.FullAddressAbsolute).»
            $ws.Names[$RangeName].Address = $Range.FullAddressAbsolute
        }
        else  {
            Write-verbose -Message «Creating Named range ‘$RangeName’ as $($Range.FullAddressAbsolute).»
            $null = $ws.Names.Add($RangeName, $Range)
        }
    }
    catch {Write-Warning -Message «Failed adding named range ‘$RangeName’ to worksheet ‘$($ws.Name)’: $_»  }
}

function Add-ExcelTable {
    <#

      .SYNOPSIS

        Adds Tables to Excel workbooks.

      .DESCRIPTION

        Unlike named ranges, where the name only needs to be unique within a sheet, Table names must be unique in the workbook

        Tables carry formatting by default have a filter. The filter, header, Totals, first and last column highlights

      .EXAMPLE

        Add-ExcelTable -Range $ws.Cells[$dataRange] -TableName $TableName

 
        $WS is a worksheet, and $dataRange is a string describing a range of cells — e.g. «A1:Z10»

        this range which will become a table, named $TableName

      .EXAMPLE

        Add-ExcelTable -Range $ws.cells[$($ws.Dimension.address)] -TableStyle Light1 -TableName Musictable -ShowFilter:$false -ShowTotal -ShowFirstColumn

        Again $ws is a worksheet, range here is the whole of the active part of the worksheet. The table style and name are set,

        the filter is turned off, and a «Totals» row added, and first column is set in bold.

    #>


    [CmdletBinding()]
    [OutputType([OfficeOpenXml.Table.ExcelTable])]
    param (
        #The range of cells to assign to a table.
        [Parameter(Mandatory=$true)]
        [OfficeOpenXml.ExcelRange]$Range,
        #The name for the Table — this should be unqiue in the Workbook.
        [Parameter(Mandatory=$true)]
        [String]$TableName,
        #The Style for the table, by default «Medium6» is used
        [OfficeOpenXml.Table.TableStyles]$TableStyle = ‘Medium6’,
        #By default the header row is shown — it can be turned off with -ShowHeader:$false.
        [Switch]$ShowHeader ,
        #By default the filter is enabled — it can be turned off with -ShowFilter:$false.
        [Switch]$ShowFilter,
        #Show total adds a totals row. This does not automatically sum the columns but provides a drop-down in each to select sum, average etc
        [Switch]$ShowTotal,
        #A HashTable in the form ColumnName = «Average»|»Count»|»CountNums»|»Max»|»Min»|»None»|»StdDev»|»Sum»|»Var» — if specified, -ShowTotal is not needed.
        [hashtable]$TotalSettings,
        #Highlights the first column in bold.
        [Switch]$ShowFirstColumn,
        #Highlights the last column in bold.
        [Switch]$ShowLastColumn,
        #By default the table formats show striped rows, the can be turned off with -ShowRowStripes:$false
        [Switch]$ShowRowStripes,
        #Turns on column stripes.
        [Switch]$ShowColumnStripes,
        #If -PassThru is specified, the table object will be returned to allow additional changes to be made.
        [Switch]$PassThru
    )
    try {
        if ([OfficeOpenXml.FormulaParsing.ExcelUtilities.ExcelAddressUtil]::IsValidAddress($TableName)) {
            Write-Warning -Message «$tableName reads as an Excel address, and so is not allowed as a table name.»
            return
        }
        if ($tableName -notMatch ‘^[A-Z]’) {
            Write-Warning -Message «$tableName is not allowed as a table name because it does not begin with a letter.»
            return
        }
        if ($TableName -match «W») {
            Write-Warning -Message «At least one character in $TableName is illegal in a table name and will be replaced with ‘_’ . «
            $TableName = $TableName -replace ‘W’, ‘_’
        }
        $ws = $Range.Worksheet
        #if the table exists in this worksheet, update it.
        if ($ws.Tables[$TableName]) {
            $tbl =$ws.Tables[$TableName]
            $tbl.TableXml.table.ref = $Range.Address
            Write-Verbose -Message «Re-defined table ‘$TableName’, now at $($Range.Address).»
        }
        elseif ($ws.Workbook.Worksheets.Tables.Name -contains $TableName) {
            Write-Warning -Message «The Table name ‘$TableName’ is already used on a different worksheet.»
            return
        }
        else {
            $tbl = $ws.Tables.Add($Range, $TableName)
            Write-Verbose -Message «Defined table ‘$TableName’ at $($Range.Address)»
        }
        #it seems that show total changes some of the others, so the sequence matters.
        if     ($PSBoundParameters.ContainsKey(‘ShowHeader’))        {$tbl.ShowHeader        = [bool]$ShowHeader}
        if     ($PSBoundParameters.ContainsKey(‘TotalSettings’))     {
            $tbl.ShowTotal = $true
            foreach ($k in $TotalSettings.keys) {
                if (-not $tbl.Columns[$k]) {Write-Warning -Message «Table does not have a Column ‘$k’.»}
                elseif ($TotalSettings[$k] -notin @(«Average», «Count», «CountNums», «Max», «Min», «None», «StdDev», «Sum», «Var») ) {
                    Write-wanring «‘$($TotalSettings[$k])’ is not a valid total function.»
                }
                else {$tbl.Columns[$k].TotalsRowFunction = $TotalSettings[$k]}
            }
        }
        elseif ($PSBoundParameters.ContainsKey(‘ShowTotal’))         {$tbl.ShowTotal         = [bool]$ShowTotal}
        if     ($PSBoundParameters.ContainsKey(‘ShowFilter’))        {$tbl.ShowFilter        = [bool]$ShowFilter}
        if     ($PSBoundParameters.ContainsKey(‘ShowFirstColumn’))   {$tbl.ShowFirstColumn   = [bool]$ShowFirstColumn}
        if     ($PSBoundParameters.ContainsKey(‘ShowLastColumn’))    {$tbl.ShowLastColumn    = [bool]$ShowLastColumn}
        if     ($PSBoundParameters.ContainsKey(‘ShowRowStripes’))    {$tbl.ShowRowStripes    = [bool]$ShowRowStripes}
        if     ($PSBoundParameters.ContainsKey(‘ShowColumnStripes’)) {$tbl.ShowColumnStripes = [bool]$ShowColumnStripes}
        $tbl.TableStyle = $TableStyle

        if ($PassThru) {return $tbl}
    }
    catch {Write-Warning -Message «Failed adding table ‘$TableName’ to worksheet ‘$WorksheetName’: $_»}
}

Like this post? Please share to your friends:
  • Powerpoint charts from excel
  • Powershell excel ширина столбца
  • Power query для excel книга
  • Powerpoint based on excel
  • Powershell excel удалить строку