The ImportExcel is a PowerShell module that allows you import to or export data directly from Excel spreadsheets without having Microsoft Excel installed on your computer. In this tutorial, you’ll learn to work with Import-Excel and Export-Excel. The ImportExcel module runs on Windows, Linux, or Mac and now can be used in Azure functions and GitHub Actions. Simply put, if you need to generate reports for work, you must learn this module.
Contents
- Importing data from Excel
- Export data to Excel
- Adding data to an existing spreadsheet
- Exporting data with formatting
- Creating charts
- Editing existing data in an Excel spreadsheet
- Conclusion and links
- Author
- Recent Posts
Mike Kanakos is a Cloud and Datacenter Microsoft MVP, tech blogger and PowerShell community leader. He writes about infrastructure management and cloud automation. You can follow Mike on his blog https://www.commandline.ninja or on Twitter at @MikeKanakos.
Doug Finke, a Microsoft MVP since 2009, builds and maintains the module. Doug is constantly improving the module and releases new module updates frequently. As of this writing, the module is at v7.1.3 and is continually being developed. His module is nearing 1 million downloads since its first release! Installing the module is a simple task with PowerShell code.
Install-Module -Name ImportExcel
Excel is not required to be installed for this module to work. The module installs a .net DLL named epplus.dll that allows the module to import Excel data or export to Excel format. This allows you to install the module on a server without having to install Office on the server.
Importing data from Excel
Getting started with the module is very easy. Let’s start by importing some data from Excel. In this first demo, I’ll be importing some simple data I have from a table in Excel.
Sample Excel table data for import
To import data, I use the Import-Excel cmdlet and specify the path. In this example, I will also save the data to a variable called «Fruit» for later use.
Import-Excel "c:tempExcelDemo.xlsx" -OutVariable Fruit
Excel data import in PowerShell
Now, we have a simple table with data organized in columns and rows. The table properties reveal that PowerShell has created a PSCustomObject with two note properties for the two columns.
Excel table properties
But what if I have a large table of data? I can specify which data gets imported without having to pull in the entire table. Let’s look at how that works.
I have created a new tab in my spreadsheet that contains all the process info from my machine. I have named the tab «Processes.» The spreadsheet has 69 columns of data. I could import all these columns and filter the data, but for this demonstration I just want the Name, ProcessName, CPU, and Memory columns.
Process info data in Excel
Using the Import-Excel cmdlet, I can pull in just the data I am interested in. Let’s pull in the columns I mentioned earlier (Name, ProcessName, CPU, and Memory). For this demo, I only want 6 rows of data. To accomplish this, I use the -ImportColumns, -StartRow and -EndRow parameters.
To pick the columns, I simply count columns from left to right in my spreadsheet starting at 1. I know you can’t see the full spreadsheet, but I have already counted out the columns that I need. To select the columns I want, I will need columns 1, 6, 12, and 46. But if I want to keep them in the order I mentioned above, then the order would have to be 1, 46, 12, and 6.
import-excel C:tempExcelDemo.xlsx -WorksheetName Processes -ImportColumns @(1, 46, 12, 6) -startrow 1 -endrow 7
Process info imported into PowerShell
Export data to Excel
As with the process of importing data, I can also export data to Excel easily with just one line of code. Let’s go back to my previous example: getting the process data. If I want to export all the process info on my machine, all I need to do is type one line:
Get-process | Export-Excel
This results in the Export-Excel cmdlet creating a spreadsheet. If I have Excel installed, it launches Excel and presents the file output to me.
Exporting data to Excel using default values
Notice that I didn’t specify a filename or any other formatting information. However, the Export-Excel cmdlet created the spreadsheet and applied some default formatting (see callout 2) and created a temporary file for me (callout 1).
Of course, I can choose a filename and path on export, if I so desire, by using the -path parameter and inputting a value like so:
Get-process | Export-Excel C:tempProcessList.xlsx
Adding data to an existing spreadsheet
At some point, you will need to add data to an existing spreadsheet. The -Append parameter adds data to an existing spreadsheet. I can specify a worksheet to add to with the -worksheet parameter or I can start a new worksheet with the same parameter but picking a new tab name.
So far, I have been working on a spreadsheet named «ExcelDemo.xlsx,» which contains the Fruit and Processes worksheets. I want to add a new tab named «People» and copy in data from a small table I created.
Table of person and city info saved to the People variable
Exporting this data to my existing Excel spreadsheet and creating a new worksheet would look like this:
$People | Export-Excel c:tempExcelDemo.xlsx -Append -WorksheetName "People"
People table export
This is easy and doesn’t require much code. Below, we can see the worksheet tabs that have been created from Export-Excel.
Excel worksheet tabs created by Export Excel
When you look at the table, you’ll see that it has none of the familiar Excel spreadsheet formatting. I would like to add some formatting to my data. Let me show you how this can be done.
Exporting data with formatting
The Export-Excel cmdlet offers many options for formatting my data on export. I’ll highlight a few options, but make sure you review the parameters available for the Export-Excel cmdlet for a full list of formatting options.
I would like to export the data again. This time, however, I will add a table style and a title for my table, and I would like the table title to be bold. This is possible with Export-Excel. The code used to do this is slightly different from the previous example:
$People | Export-Excel c:tempExcelDemo.xlsx -Append -WorksheetName "PeopleFormatted" -TableStyle Medium16 -title "Demo of Table Formatting" -TitleBold
Formatted version of the People table in Excel
You might wonder what the table style I selected (Medium16) in the last example is. The Export-Excel cmdlet has table styles built in that correspond to the table styles you see in Excel.
Export Excel table styles available
The table styles in Excel are the same. In the screen cap below, I clicked on the «Format As Table» at the top of the spreadsheet, which then displays the table styles. If you hover your mouse over a style, you’ll see some text that provides you the style details. The #1 callout is the style I hovered over. Notice that it says Medium16. This is how I got the name that I used in my previous code example for the table style parameter.
Corresponding Excel table styles
Creating charts
Export-Excel does more than just make spreadsheets. The cmdlet can export table data and turn that data into a chart inside an Excel spreadsheet. For my next example, I have created a table of some simple inventory items and sales data.
Sales data
I would like to chart these sales in a simple bar graph that depicts units sold. To do this, I need to define the properties I want for my table. To do this, I use the New-ExcelChartDefinition cmdlet.
$ChartData = New-ExcelChartDefinition -XRange Item -YRange TotalSold -ChartType ColumnClustered -Title "Total Fruit Sales"
This line of code defines my table properties, and it tells Excel what to use for the xValue in the chart. I first use the Item column, then, I define the yValue (I am using the TotalSold column). Then, I specify a chart type. There are 69 chart types available in the cmdlet, all of which correspond to the chart types in Excel. I chose the «ColumnClustered» type for my example.
I then add a chart title, although this is not required. These values are saved to a variable named $ChartData. The next piece to add to the export cmdlet is this chart definition:
$data | Export-Excel C:tempExcelDemo.xlsx -Append -WorksheetName FruitSalesChart -ExcelChartDefinition $ChartData -AutoNameRange -show -Title "Fruit Sales"
Let’s walk through this example. First, I send the $data variable to the Export-Excel cmdlet. The $data variable is our sales data. The syntax for Export-Excel is a continuation from my previous example. I export and append this to a spreadsheet named «ExcelDemo.xlsx.» I create new worksheet tab named FruitSalesChart. This is all code we saw in the previous examples.
Then, I am add in the chart definition I created earlier by calling the $ChartData variable. Finally, I tell Excel that I want an auto name range. The -show parameter auto opens the spreadsheet after I create it.
Fruit Sales exported to Excel as a table and chart
Editing existing data in an Excel spreadsheet
I find it so easy to export data from PowerShell to Excel that I default to the Export-Excel cmdlet for much of my work. However, you can also update individual data values in an existing spreadsheet. I will connect to the spreadsheet that I used in the previous examples. To connect, use the Open-ExcelPackage cmdlet.
$ExcelPkg = Open-ExcelPackage -Path "C:tempExcelDemo.xlsx"
I can start to work with the data after opening the file.
Spreadsheet info in PowerShell
The first five rows constitute the worksheet tabs I created earlier in the spreadsheet. I can view the data in any of the tabs with some simple code.
#Let's access the data in the "PeopleFormatted" worksheet $WorkSheet = $ExcelPkg.Workbook.Worksheets["PeopleFormatted"].Cells $WorkSheet[3,1] | select value Value ----- Jeremy $WorkSheet[3,2] | select value Value ----- Loxahatchee
The code above probably doesn’t make much sense without a visual reference. Have a look at this screen cap below, which should help explain the code.
In the first code example, I called $WorkSheet[3,1] . If you look at the Excel spreadsheet, «3» represents the 3rd row. «1» represents the first column (starting from left of column A).
In the second code example, I called $WorkSheet[3,2] which is Row 3, Column2 (column B in spreadsheet).
Example of accessing Excel data values
Inserting a new value into the Excel data cell is done with a similar set of code. I will replace the name «Jeremy» with the name «Robert».
$WorkSheet[3,1].Value = "Robert" $WorkSheet[3,1] | select value Value ----- Robert
It’s that easy to update a field in Excel! However, there’s one catch. This change I just made is still in memory inside PowerShell. The file needs to «closed» for the data to be written back into the file.
Close-ExcelPackage $ExcelPkg
Updated spreadsheet value
Conclusion and links
Today, I showed you how to import data from an Excel spreadsheet, create a spreadsheet, create a simple chart, and manipulate the imported data in an existing Excel spreadsheet. The ImportExcel module makes these tasks and others operations simple to complete.
I have touched upon a just few of the many complex tasks you can perform with this module. If you would like to learn more, please visit Doug Finke’s GitHub page for many more examples of demo code you can try for yourself. He has a page dedicated to FAQs and a thorough analysis on examples that you should definitely check out.
Subscribe to 4sysops newsletter!
Many of the code examples in Doug’s module come from community members looking to use Excel in unique ways. If you have ideas for new ways to use his module, please submit a pull request to his repo so that others can learn from your use case.
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 wayExport-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'
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
The
Export-Excel
cmdlet has a ton of parameters you can use to create Excel workbooks of all kinds. For a full rundown on everythingExport-Excel
can do, runGet-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'
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 everythingImport-Excel
can do, runGet-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 usingNew-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!
As of now, there is no built-in command like CSV (Export-CSV) to export output to the excel file but we can use the Out-File command to export data to excel or any other file format.
Let’s use Out-File to export the output of the Get-Processes command to an excel file.
Get-Process | Out-File C:Tempprocesses.xls
The above command will get all the running processes on the local system to the excel file. Let’s check the output of the excel file. You can see that the output is not in the proper excel format.
One other way is to install the ImportExcel module for excel. It is a very popular module to work with excel files.
To install the ImportExcel module, you need to run the below command to get it installed from the PowerShell gallery.
Install-Module ImportExcel -AllowClobber -Force
Once you install it, you need to import the module in the current PowerShell session if not imported.
Get-Module ImportExcel -ListAvailable | Import-Module -Force -Verbose
Once you have this module loaded in PowerShell, you can run the below command to export output into the excel format.
Get-Process | Export-Excel -Path C:TempProcesses.xlsx
Output
Данный материал является переводом оригинальной статьи «ATA Learning : Adam Bertram : PowerShell and Excel: Seize the Power!».
Microsoft Excel — один из тех вездесущих инструментов, от которых большинство из нас не может уйти, даже если хочет. Многие ИТ-специалисты используют Excel, как небольшую базу данных, в которой хранятся тонны данных в различных процедурах автоматизации. Каков наилучший сценарий автоматизации и Excel? Это, например, PowerShell!
Работу с таблицами Excel непросто автоматизировать. В отличие от менее функционального (и более простого) аналога файла CSV, книги Excel — это не просто текстовые файлы. Для работы со сложными книгами Excel потребует от PowerShell манипуляции с Component Object Model (COM), для чего раньше нужно было установить Excel. Однако, на самом деле, это вовсе не обязательно. Например, проницательный участник сообщества PowerShell, Doug Finke, создал модуль PowerShell, названный ImportExcel. Модуль устраняет сложность работы с Excel и позволяет легко работать с книгами Excel через PowerShell сценарии!
В этой статье рассмотрим пример того, что можно сделать в PowerShell и Excel с помощью модуля ImportExcel, а также рассмотрим несколько популярных вариантов использования.
Предварительные требования
При запуске модуля ImportExcel в системе Windows отдельные зависимости не требуются. Однако, если вы работаете с MacOS, вам необходимо установить пакет mono-libgdiplus, используя команду вида:
brew install mono-libgdiplus
Примечание: Все примеры в этой статье будут построены с использованием macOS, но все они должны работать и на других платформах. При использовании macOS, не забудьте перезапустить сеанс PowerShell, прежде чем продолжить.
Установка модуля ImportExcel
Начните с загрузки и установки модуля через PowerShell Gallery, запустив:
Install-Module ImportExcel -Scope CurrentUser
Через несколько секунд все будет в порядке.
Использование PowerShell для экспорта в рабочий лист Excel
Возможно, вы знакомы со стандартными командлетами PowerShell Export-Csv и Import-Csv. Эти командлеты позволяют читать и экспортировать объекты PowerShell в файлы CSV. К сожалению, в PowerShell нет таких же встроенных командлетов для Excel. Но, используя модуль ImportExcel, вы можете создать такой функционал!
Один из наиболее частых запросов системного администратора — это экспорт объектов PowerShell в рабочий лист Excel. С помощью командлета Export-Excel из модуля ImportExcel, вы можете легко сделать это. Командлет Export-Excel принимает любой объект точно так же, как делает Export-Csv. Этому командлету можно передать любой объект.
Например, возможно, вам нужно найти какие-то процессы, запущенные на вашем локальном компьютере, и поместить их в книгу Excel.
Чтобы найти процессы, запущенные в системе с помощью PowerShell, используйте командлет Get-Process, который возвращает каждый запущенный процесс и различную информацию о каждом процессе. Чтобы экспортировать эту информацию в Excel, используйте командлет Export-Excel, указывающий путь к создаваемой книге Excel. Вы можете увидеть пример команды и снимок экрана сгенерированного файла Excel ниже.
Get-Process | Export-Excel -Path './processes.xlsx
Поздравляем! Вы экспортировали всю информацию точно так же, как Export-Csv, но, в отличие от Export-Csv, мы можем сделать эти данные намного интереснее. Убедитесь, что имя рабочего листа называется «Proccesses», данные находятся в таблице, а размер строк устанавливается автоматически.
Добавим к командлету параметр -AutoSize для автоматического изменения размера всех строк, -TableName, чтобы указать имя таблицы, которая будет включать все данные, и имя параметра -WorksheetName для процессов, и сможем увидеть на снимке экрана ниже, что в итоге получится.
Get-Process | Export-Excel -Path './processes.xlsx' -AutoSize -TableName 'Processes' -WorksheetName 'Proccesses'
Командлет Export-Excel имеет множество параметров, которые можно использовать для создания книг Excel всех видов. Для получения полной информации о возможностях Export-Excel, запустите:
Get-Help Export-Excel
Использование PowerShell для импорта в Excel
Итак, ранее вы экспортировали некоторую информацию в файл с именем process.xlsx. Возможно, теперь вам нужно переместить этот файл на другой компьютер и импортировать / прочитать эту информацию. Командлет Import-Excel к вашим услугам.
При простейшем использовании вам нужно только указать путь к документу / книге Excel с помощью параметра -Path, как показано ниже. Вы увидите, что он читает первый рабочий лист, в данном случае рабочий лист «Processes», и возвращает объекты PowerShell.
Import-Excel -Path './processes.xlsx'
Может быть, у вас есть несколько листов в книге Excel? Вы можете прочитать конкретный рабочий лист с помощью параметра -WorkSheetname.
Import-Excel -Path './processes.xlsx' -WorkSheetname 'SecondWorksheet'
Вам нужно читать только определенные столбцы из рабочего листа Excel? Используйте параметр -HeaderName, чтобы указать только те параметры, которые вы хотите прочитать.
Import-Excel -Path './processes.xlsx' –WorkSheetname 'Processes' -HeaderName 'CPU','Handle'
Командлет Import-Excel имеет другие параметры, которые можно использовать для чтения книг Excel всех типов. Чтобы получить полное изложение всего, что может делать Import-Excel, запустите:
Get-Help Import-Excel
Использование PowerShell для получения (и установки) значений ячеек Excel
Теперь вы знаете, как читать весь лист Excel с помощью PowerShell. Но что, если вам нужно только одно значение ячейки? Технически вы можете использовать Import-Excel и отфильтровать нужное значение с помощью Where-Object, но это будет не слишком эффективно.
Вместо этого, используя командлет Open-ExcelPackage, вы можете «преобразовать» книгу Excel в объект PowerShell, который затем можно будет читать и изменять. Этот командлет аналогичен использованию New-Object -ComObject ‘Excel.Application’, если работать напрямую с COM-объектами.
Чтобы найти значение ячейки, сначала откройте книгу Excel, чтобы занести его в память. Затем выберите лист внутри книги.
$excel = Open-ExcelPackage -Path './processes.xlsx'
$worksheet = $excel.Workbook.Worksheets['Processes']
Этот процесс похож на способ открытия книг с помощью COM-объекта ‘Excel.Workbooks.Open’.
После того, как рабочий лист назначен переменной, вы можете перейти к отдельным строкам, столбцам и ячейкам. Возможно, вам нужно найти все значения ячеек в строке A1. Вам просто нужно сослаться на свойство ‘Cells’, указав индекс A1, как показано ниже.
$worksheet.Cells['A1'].Value
Вы также можете изменить значение ячеек на листе, присвоив другое значение, например:
$worksheet.Cells['A1'] = 'differentvalue'
Будучи хранимым в оперативной памяти, важно высвобождать пакет Excel с помощью командлета Close-ExcelPackage.
Close-ExcelPackage $excel
Конверсия Excel в файлы CSV с помощью PowerShell
Если у вас есть содержимое листа Excel, представленное с помощью объектов PowerShell, преобразование листов Excel в CSV просто требует отправки этих объектов в командлет Export-Csv.
Используя созданную ранее книгу processes.xlsx, прочтите первый рабочий лист, который получает все данные в объекты PowerShell, а затем экспортируйте эти объекты в CSV с помощью приведенной ниже команды.
Import-Excel './processes.xlsx' | Export-Csv -Path './processes.csv' -NoTypeInformation
Конверсия множества рабочих листов
Если у вас есть книга Excel с несколькими листами, вы также можете создать файл CSV для каждого листа. Для этого вы можете найти все листы в книге с помощью командлета Get-ExcelSheetInfo. Когда у вас есть имена рабочих листов, вы можете передать их в параметр -WorksheetName, а также использовать имя листа в качестве имени файла CSV.
Ниже вы можете найти необходимый пример кода.
$sheets = (Get-ExcelSheetInfo -Path './processes.xlsx').Name
foreach ($sheet in $sheets) {
Import-Excel -WorksheetName $sheet -Path './processes.xlsx' | Export-Csv "./$sheet.csv" -NoTypeInformation
}
Заключение
Используя модуль ImportExcel из библиотеки модулей PowerShell, вы можете импортировать, экспортировать и управлять данными в книгах Excel точно так же, как и в CSV, без установки Excel!
##############################################################################################
#Just change the
below
parameters
$DirectoryToSave=
'C:'
$Filename=
'DatabaseDetails'
$From =
'pjayaram@cts.com'
$To =
'<To Address>'
# for example abcd@xyz.com
$SMTP=
'<SMTP>'
$DSN =
' <DSN Name'
# constants.
$xlCenter=
-4108
$xlTop=
-4160
$xlOpenXMLWorkbook=[int]
51
# and we put the queries in here
# You can replace the SQL - Depends on your requirement. In this case, I've used to list the database details
$SQL=@"
USE MASTER
SELECT @@SERVERNAME Servername,
CONVERT(VARCHAR(
25
), DB.name) AS dbName,
CONVERT(VARCHAR(
10
), DATABASEPROPERTYEX(name,
'status'
)) AS [Status],
(SELECT COUNT(
1
) FROM sysaltfiles WHERE DB_NAME(dbid) = DB.name AND groupid !=
0
) AS DataFiles,
(SELECT SUM((size*
8
)/
1024
)
FROM sysaltfiles WHERE DB_NAME(dbid) = DB.name AND groupid!=0
) AS [Data MB],
(SELECT COUNT(
1
) FROM sysaltfiles WHERE DB_NAME(dbid) = DB.name AND groupid=
0
)
AS LogFiles,
(SELECT SUM((size*
8
)/
1024
)
FROM sysaltfiles WHERE DB_NAME(dbid) = DB.name AND groupid=0
) AS [Log MB],
(SELECT SUM((size*
8
)/
1024
)
FROM sysaltfiles WHERE DB_NAME(dbid) = DB.name AND groupid!=0
)+(SELECT SUM((size*
8
)/
1024
)
FROM sysaltfiles WHERE DB_NAME(dbid) = DB.name AND groupid=0
) TotalSizeMB,
convert(sysname,DatabasePropertyEx(name,
'Updateability'
)) Updateability,
convert(sysname,DatabasePropertyEx(name,
'UserAccess'
)) UserAccess ,
convert(sysname,DatabasePropertyEx(name,
'Recovery'
)) RecoveryModel ,
convert(sysname,DatabasePropertyEx(name,
'Version'
)) Version ,
CASE cmptlevel
WHEN
60
THEN
'60 (SQL Server 6.0)'
WHEN
65
THEN
'65 (SQL Server 6.5)'
WHEN
70
THEN
'70 (SQL Server 7.0)'
WHEN
80
THEN
'80 (SQL Server 2000)'
WHEN
90
THEN
'90 (SQL Server 2005)'
WHEN
100
THEN
'100 (SQL Server 2008)'
END AS [compatibility
level
],
CONVERT(VARCHAR(
20
), crdate,
103
) +
' '
+ CONVERT(VARCHAR(
20
), crdate,
108
) AS [Creation date],
ISNULL((SELECT TOP
1
CASE TYPE WHEN
'D'
THEN
'Full'
WHEN
'I'
THEN
'Differential'
WHEN
'L'
THEN 'Transaction log'
END + ' – '
+
LTRIM(ISNULL(STR(ABS(DATEDIFF(DAY, GETDATE(),Backup_finish_date))) +
' days ago'
,
'NEVER'
)) +
' – '
+
CONVERT(VARCHAR(
20
), backup_start_date,
103
) +
' '
+ CONVERT(VARCHAR(
20
), backup_start_date,
108
) +
' – '
+
CONVERT(VARCHAR(
20
), backup_finish_date,
103
) +
' '
+ CONVERT(VARCHAR(
20
), backup_finish_date,
108
) +
' ('
+ CAST(DATEDIFF(second, BK.backup_start_date,
BK.backup_finish_date) AS VARCHAR(
4
)) +
' '
+
'seconds)'
FROM msdb.dbo.backupset BK WHERE BK.database_name = DB.name ORDER BY backup_set_id DESC),
'-'
)
AS [Last backup]
FROM sysdatabases DB
ORDER BY dbName, [Last backup] DESC, NAME
"@
#Create an Excel file to save the data
# if the directory doesn't exist, then create it
if (!(Test-Path -path
"$DirectoryToSave"
)) #create it if not existing
{
New-Item
"$DirectoryToSave"
-type directory | out-null
}
$excel = New-Object -Com Excel.Application #open a new instance of Excel
$excel.Visible = $True #make it
visible
(for debugging more than anything)
$wb = $Excel.Workbooks.Add() #create a workbook
$currentWorksheet=
1
#there are three open worksheets you can fill up
if ($currentWorksheet-lt
4
)
{
$ws = $wb.Worksheets.Item($currentWorksheet)
}
else
{
$ws = $wb.Worksheets.Add()
}
#add
if it doesn't exist
$currentWorksheet +=
1
#keep a tally
# You can refresh it
$qt = $ws.QueryTables.Add(
"ODBC;DSN=$DSN"
, $ws.Range(
"A1"
),
$SQL)
# and execute it
if ($qt.Refresh()) #if the routine works OK
{
$ws.Activate()
$ws.Select()
$excel.Rows.Item(
1
).HorizontalAlignment = $xlCenter
$excel.Rows.Item(
1
).VerticalAlignment = $xlTop
$excel.Rows.Item(
"1:1"
).Font.Name =
"Calibri"
$excel.Rows.Item(
"1:1"
).Font.Size =
11
$excel.Rows.Item(
"1:1"
).Font.Bold = $true
$Excel.Columns.Item(
1
).Font.Bold = $true
}
$filename =
"$DirectoryToSaveTo$filename.xlsx"
#save it according to its title
if (test-path $filename ) { rm $filename } #delete the file if it already exists
$wb.SaveAs($filename, $xlOpenXMLWorkbook) #save as an XML Workbook (xslx)
$wb.Saved = $True #flag it as being saved
$wb.Close() #close the document
$Excel.Quit() #and the instance of Excel
$wb = $Null #set
all
variables that point to Excel objects to null
$ws = $Null #makes sure Excel deflates
$Excel=$Null #let the air out
#Function to send email with an attachment
Function sendEmail([string]$emailFrom, [string]$emailTo, [string]$subject,[string]$body,[string]$smtpServer,[string]$filePath)
{
#initate message
$email = New-Object System.Net.Mail.MailMessage
$email.From = $emailFrom
$email.To.Add($emailTo)
$email.Subject = $subject
$email.Body = $body
# initiate email attachment
$emailAttach = New-Object System.Net.Mail.Attachment $filePath
$email.Attachments.Add($emailAttach)
#initiate sending email
$smtp = new-object Net.Mail.SmtpClient($smtpServer)
$smtp.Send($email)
}
#Call Function
sendEmail -emailFrom $from -emailTo $to -subject
"Database Details"
-body "Database Information"
-smtpServer $SMTP -filePath $filename