Read Excel sheet in Powershell - excel

The below script reads the sheet names of an Excel document....
How could I improve it so it could extract all the contents of column B (starting from row 5 - so row 1-4 are ignored) in each worksheet and create an object?
E.g. if column B in worksheet 1 (called London) has the following values:
Marleybone
Paddington
Victoria
Hammersmith
and column C in worksheet 2 (called) Nottingham has the following values:
Alverton
Annesley
Arnold
Askham
I'd want to create a object that from that looks like this:
City,Area
London,Marleybone
London,Paddington
London,Victoria
London,Hammersmith
Nottingham,Alverton
Nottingham,Annesley
Nottingham,Arnold
Nottingham,Askham
This is my code so far:
clear all
sheetname = #()
$excel=new-object -com excel.application
$wb=$excel.workbooks.open("c:\users\administrator\my_test.xls")
for ($i=1; $i -le $wb.sheets.count; $i++)
{
$sheetname+=$wb.Sheets.Item($i).Name;
}
$sheetname

This assumes that the content is in column B on each sheet (since it's not clear how you determine the column on each sheet.) and the last row of that column is also the last row of the sheet.
$xlCellTypeLastCell = 11
$startRow = 5
$col = 2
$excel = New-Object -Com Excel.Application
$wb = $excel.Workbooks.Open("C:\Users\Administrator\my_test.xls")
for ($i = 1; $i -le $wb.Sheets.Count; $i++)
{
$sh = $wb.Sheets.Item($i)
$endRow = $sh.UsedRange.SpecialCells($xlCellTypeLastCell).Row
$city = $sh.Cells.Item($startRow, $col).Value2
$rangeAddress = $sh.Cells.Item($startRow + 1, $col).Address() + ":" + $sh.Cells.Item($endRow, $col).Address()
$sh.Range($rangeAddress).Value2 | foreach
{
New-Object PSObject -Property #{ City = $city; Area = $_ }
}
}
$excel.Workbooks.Close()

Sorry I know this is an old one but still felt like helping out ^_^
Maybe it's the way I read this but assuming the excel sheet 1 is called "London" and has this information; B5="Marleybone" B6="Paddington" B7="Victoria" B8="Hammersmith". And the excel sheet 2 is called "Nottingham" and has this information; C5="Alverton" C6="Annesley" C7="Arnold" C8="Askham". Then I think this code below would work. ^_^
$xlCellTypeLastCell = 11
$startRow = 5
$excel = new-object -com excel.application
$wb = $excel.workbooks.open("C:\users\administrator\my_test.xls")
for ($i = 1; $i -le $wb.sheets.count; $i++)
{
$sh = $wb.Sheets.Item($i)
$endRow = $sh.UsedRange.SpecialCells($xlCellTypeLastCell).Row
$col = $col + $i - 1
$city = $wb.Sheets.Item($i).name
$rangeAddress = $sh.Cells.Item($startRow, $col).Address() + ":" + $sh.Cells.Item($endRow, $col).Address()
$sh.Range($rangeAddress).Value2 | foreach{
New-Object PSObject -Property #{City = $city; Area=$_}
}
}
$excel.Workbooks.Close()
This should be the output (without the commas):
City, Area
---- ----
London, Marleybone
London, Paddington
London, Victoria
London, Hammersmith
Nottingham, Alverton
Nottingham, Annesley
Nottingham, Arnold
Nottingham, Askham

This was extremely helpful for me when trying to automate Cisco SIP phone configuration using an Excel spreadsheet as the source. My only issue was when I tried to make an array and populate it using $array | Add-Member ... as I needed to use it later on to generate the config file. Just defining an array and making it the for loop allowed it to store correctly.
$lastCell = 11
$startRow, $model, $mac, $nOF, $ext = 1, 1, 5, 6, 7
$excel = New-Object -ComObject excel.application
$wb = $excel.workbooks.open("H:\Strike Network\Phones\phones.xlsx")
$sh = $wb.Sheets.Item(1)
$endRow = $sh.UsedRange.SpecialCells($lastCell).Row
$phoneData = for ($i=1; $i -le $endRow; $i++)
{
$pModel = $sh.Cells.Item($startRow,$model).Value2
$pMAC = $sh.Cells.Item($startRow,$mac).Value2
$nameOnPhone = $sh.Cells.Item($startRow,$nOF).Value2
$extension = $sh.Cells.Item($startRow,$ext).Value2
New-Object PSObject -Property #{ Model = $pModel; MAC = $pMAC; NameOnPhone = $nameOnPhone; Extension = $extension }
$startRow++
}
I used to have no issues adding information to an array with Add-Member but that was back in PSv2/3, and I've been away from it a while. Though the simple solution saved me manually configuring 100+ phones and extensions - which nobody wants to do.

There is the possibility of making something really more cool!
# Powershell
$xl = new-object -ComObject excell.application
$doc=$xl.workbooks.open("Filepath")
$doc.Sheets.item(1).rows |
% { ($_.value2 | Select-Object -first 3 | Select-Object -last 2) -join "," }

You can use ImportExcel
which uses OfficeOpenXml

Related

is it possible to read an Excel through powershell like this?

I have this excel
every row is an automation script I need to execute with certain parameters, the excel is because every script receives different parameters, and I need to do a powershell script that reads the excel file and for each row, execute that process id(script) and send those parameters
is there a way to do that? is it doable?
so far I have this
$file = "C:\Users\MX02689\Documents\Parametros.xlsx"
$sheetName = "Sheet1"
$objExcel = New-Object -ComObject Excel.Application
$workbook = $objExcel.Workbooks.Open($file)
$sheet = $workbook.Worksheets.Item($sheetName)
$objExcel.Visible=$false
$rowMax = ($sheet.UsedRange.Rows).count
$colMax = ($sheet.UsedRange.Columns).count
$rowName,$colName = 1,1
#the idea here is that for each row that has values do this
for($i=1;$i-le $colMax-1; $i++)
#The idea here is that if (parameter 1 -eq 1 ){
execute the command we use to send the scripts process id; "parameter2 parameter 3 parameter 4"
}else{
skip the row and go to the next one
}
{
Write-Output("" + $sheet.Cells.Item($rowName,$colName+$i).text)
}
am I in the right direction? thank you for the help :)
am I in the right direction? is it doable what Im trying to do? is there a optimized way to achieve this? thank you for your help :)
Greetings
Using Excel is not the fastest or easiest way of doing this with PowerShell.
It can be done like this:
$file = "D:\Parametros.xlsx"
$objExcel = New-Object -ComObject Excel.Application
$workbook = $objExcel.Workbooks.Open($file)
$sheet = $workbook.Worksheets.Item(1)
$objExcel.Visible = $false
$rowMax = ($sheet.UsedRange.Rows).count
$colMax = ($sheet.UsedRange.Columns).count
for ($row = 2; $row -le $rowMax; $row++) { # skip the header row
$params = #()
for ($col = 1; $col -le $colMax; $col++) {
$params += $sheet.Cells.Item($row, $col).Value()
}
# execute the command. For demo, just show the parameters used
'Invoke-Command parameters: {0}' -f ($params -join ', ')
}
$objExcel.Quit()
# clean-up used Com objects
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($sheet) | Out-Null
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($workbook) | Out-Null
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($objExcel) | Out-Null
[System.GC]::Collect()
[System.GC]::WaitForPendingFinalizers()
Far more convenient would be to save your Excel file as CSV and use that:
Import-Csv -Path 'D:\Parametros.csv' | ForEach-Object {
# execute the command. For demo, just show the parameters used
'Invoke-Command parameters: {0}, {1}, {2}, {3}' -f $_.'process id', $_.parameter1, $_.parameter2, $_.parameter3, $_.parameter4
}
Demo output for both methods:
Invoke-Command parameters: 235522, 1, testinguser3, Mko12345, something
Invoke-Command parameters: 235266, 0, testinguser4, Mko12346, something
Invoke-Command parameters: 235266, 1, testinguser5, Mko12347, something
From your comment, I now understand what the "1" or "0" means in parameter1.
Below find the adjusted codes for Excel aswell as the CSV method:
Method for Excel:
$file = "D:\Parametros.xlsx"
$objExcel = New-Object -ComObject Excel.Application
$workbook = $objExcel.Workbooks.Open($file)
$sheet = $workbook.Worksheets.Item(1)
$objExcel.Visible = $false
$rowMax = ($sheet.UsedRange.Rows).count
$colMax = ($sheet.UsedRange.Columns).count
for ($row = 2; $row -le $rowMax; $row++) { # skip the header row
$params = #()
for ($col = 1; $col -le $colMax; $col++) {
$params += $sheet.Cells.Item($row, $col).Value()
}
# if the second parameter value converted to int = 1, proceed; if 0 skip the line
if ([int]$param[1] -ne 0) {
# execute the command. For demo, just show the parameters used
'Invoke-Command parameters: {0}' -f ($params -join ', ').TrimEnd(", ")
}
}
$objExcel.Quit()
# clean-up used Com objects
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($sheet) | Out-Null
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($workbook) | Out-Null
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($objExcel) | Out-Null
[System.GC]::Collect()
[System.GC]::WaitForPendingFinalizers()
Method for CSV file:
Import-Csv -Path 'D:\Parametros.csv' | ForEach-Object {
# get the field values from the row in array $params (not a fixed number of fields)
$params = #($_.PsObject.Properties).Value
# if the second parameter value converted to int = 1, proceed; if 0 skip the line
if ([int]$params[1] -ne 0) {
# execute the command. For demo, just show the parameters used
'Invoke-Command parameters: {0}' -f ($params -join ', ').TrimEnd(", ")
}
}

need some help getting powershell do delete cell content and inserting a formula

Here is the script as it sits. $of is set to the name of the file that gets downloaded with wget. I am getting exception from HRESULT: 0x0800A03EC which has something to do with the range portion and it seeing a 0 based range, but I am giving it 2 : # of rows.
How can I get PowerShell to clear the range and then insert the formula?
#open the downloaded worksheet
$Excel = New-Object -Com Excel.Application
$Workbook = $Excel.Workbooks.Open($of)
$page = 'Project Summary'
$ws = $Workbook.Worksheets | Where-Object {$_.Name -eq $page}
# Set variables for the worksheet cells, and for navigation
$cells = $ws.Cells
$row = 1
$col = 5
# Add the header to the worksheet
$headers = "Region"
$headers | foreach {
$cells.Item($row, $col) = $_
}
# Add the formula to each occupied row
$rows = $worksheet.UsedRange.Rows.Count
$ws.Range("E2:E" + $rows).Clear()
$ws.Range("E2:E" + $rows).Formula = "=SUM(E2:E5)"
$Excel.Visible = $true
$Excel.DisplayAlerts = $false
$Excel.ActiveWorkbook.SaveAs('W:\test.xlsx')
I also tried
$rows | foreach {
$ws.Cells("E" + $rows).Clear()
$ws.Cells("E" + $rows).Formula = "=SUM(E2:E5)"
}
That gives me a Value does not fall within the expected range error.
How can I get this to clear each cell in the range E2:E<lastRow> and then insert a formula?
I have gone back to the following after finding a way to escape the entire formula using #' ... '#; there was clearly an error in my escape sequence earlier, but the following is not performing exactly as expected either.
$ws.Range("E2:E$rows").Clear();
$ws.Range("E2:E$rows").Formula = $Formula1
This now populates the formula, but it comes in as text and not as a formula; I have to solve for this.
#open the downloaded worksheet
$Excel = New-Object -Com Excel.Application
$Workbook = $Excel.Workbooks.Open($of)
$page = 'Project Summary'
$ws = $Workbook.Worksheets | Where-Object {$_.Name -eq $page}
# Set variables for the worksheet cells, and for navigation
$cells = $ws.Cells
$row = 1
$col = 5
# Add the header to the worksheet
$headers = "Region"
#open the downloaded worksheet
$excel = New-Object -Com Excel.Application
$Workbook = $Excel.Workbooks.Open($of)
$page = 'Project Summary'
$ws = $Workbook.worksheets | where-object {$_.Name -eq $page}
$Formula1 = #"
=SUM(E2:E5)
"#
$cells=$ws.Cells
$row=1
$col=5
$range = $ws.UsedRange
$rows = $range.Rows.Count
$ws.Range("E2:E$rows").Clear();
$ws.Range("E2:E$rows").Formula = $Formula1
# Add the header to the worksheet
$headers = "Region"
$headers | foreach {
$cells.item($row, $col) = $_
}
$excel.visible = $true
$excel.DisplayAlerts = $False
$excel.ActiveWorkbook.SaveAs('W:\Test.xlsx')
$excel.Quit()
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($excel)
Remove-Item $of
This is the outcome. Escaping may or may not have been the original issue, but the help here guided me to a better way to deal with it if it was the issue. I still never solved why the loop was giving the value error, but this works so I won't have to tackle that yet; that is the next script which this post will also help me with.

PowerShell saving excel sheet in unreadable format

I have the below piece of code that checks for Files to Tapes jobs for a database and gives the output in an excel sheet.
$date = Get-Date
$day = $date.Day
$hour = $date.Hour
$Excel = New-Object -ComObject Excel.Application
$Excel.visible = $true
$Excel.DisplayAlerts = $false
$Workbook = $Excel.Workbooks.Add()
$Sheet = $Excel.Worksheets.Item(1)
#Counter variable for rows and columns
$intRow = 1
$intCol = 1
$Sheet.Cells.Item($intRow,1) = "Tasks/Servers"
$Sheet.Cells.Item($intRow,2) = "DateLastRun"
$Sheet.Cells.Item($intRow,3) = "PRX1CSDB01"
$Sheet.Cells.Item($intRow,4) = "PRX1CSDB02"
$Sheet.Cells.Item($intRow,5) = "PRX1CSDB03"
$Sheet.Cells.Item($intRow,6) = "PRX1CSDB11"
$Sheet.Cells.Item($intRow,7) = "PRX1CSDB12"
$Sheet.Cells.Item($intRow,8) = "PRX1CSDB13"
$Sheet.Cells.Item($intRow+1,1) = "File To Tape weekly Full Backup"
$Sheet.UsedRange.Rows.Item(1).Borders.LineStyle = 1
#FTT.txt contains the path for a list of servers
$path = Get-Content D:\Raghav\DB_Integrated\FTT.txt
foreach ($server in $path)
{
If (Test-Path $server)
{
$BckpWeek = gci -path $server | select-object | where {$_.Name -like "*logw*"} | sort LastWriteTime | select -last 1
$Sheet.Cells.Item($intRow+1,$intCol+1) = $BckpWeek.LastWriteTime.ToString('MMddyyyy')
$Sheet.UsedRange.Rows.Item($intRow).Borders.LineStyle = 1
$x = (get-date) - ([datetime]$BckpWeek.LastWriteTime)
if( $x.days -gt 7){$status_week = "Failed"}
else{$status_week = "Successful"}
$Sheet.Cells.Item($intRow+1,$intCol+2) = $status_week
$intCol++
}
else
{
$Sheet.Cells.Item($intRow+1,$intCol+2) = "Path Not Found"
$intCol++
}
}
$Sheet.UsedRange.EntireColumn.AutoFit()
$workBook.SaveAs("C:\Users\Output.xlsx",51)
$excel.Quit()
However, when I try to import the contents of Output.xlsx into a variable say $cc, I get data in an unreadable format.
$cc = Import-Csv "C:\Users\Output.xlsx"
Attached is the image for what I get on exporting output.xlsx into $cc. I tried to put the output in csv format too. But that also doesnt seem to help.Anybody having any idea on this or having faced any similar situation before?
#ZevSpitz - Looking for the OleDbConnection class, I landed up at https://blogs.technet.microsoft.com/pstips/2014/06/02/get-excel-data-without-excel/ . This is what I was looking for. Thank you for pointing me out in the right direction.
#MikeGaruccio - Unfortunately, I didn't find Import-Excel command in Get-Help menu. I am using Powershell 4.0. Anyways, thank you for the suggestion.

Pulling Columns from Excel

ExampleData
I'm trying to pull from a total of 6 columns from an excel worksheet. I'm using a modified script from another post on stack, it looks like this.
$strPath = "C:\Users\User\Documents\EXEL\fj.xls"
$AssetInv = "C:\Users\User\Documents\EXEL\fj.txt"
$objExcel = New-Object -ComObject Excel.Application
$objExcel.Visible = $false
$WorkBook = $objExcel.Workbooks.Open($strPath)
$worksheet = $workbook.sheets.item("Daily Price Quote - Better Of -")
$intRowMax = ($worksheet.UsedRange.Rows).count
#$StartRow = 2
#$site = 1
#$state = 3
#$retailprice = 18
#$yourprice = 20
#$SavingsTotal = 21
Write "`Site City State retailprice yourprice savingstotal" | Out-File $AssetInv
Write "--------------- ------------------- -------------------- -----------------------------" |
Out-FIle $AssetInv -Append
Write-Host "Processing: " $intRowMax "rows"
for ($intRow = 7 ; $intRow -le $intRowMax ; $intRow++) {
$site = $worksheet.cells.item($intRow, 10).value2
$city = $worksheet.cells.item($intRow, 2).value2
$state = $worksheet.cells.item($intRow, 3).value2
$retailprice = $worksheet.cells.item($intRow, 18).value2
$yourprice = $worksheet.cells.item($intRow, 20).value2
$SavingsTotal = $worksheet.cells.item($intRow, 21).value2
if (($site -ge 1 )) {
"{0, -15} {1, -30} {2, -25} {3, -25}" -f $site, $city, $state, $retailprice, $yourprice, $Savingstotal |
Out-File $AssetInv -Append
}
}
$objexcel.quit()
Currently I am pulling no data, earlier I had it working for a maximum of 3 records. Any insight as to what I am doing wrong?
Ok, we'll start with your code to get the worksheet we want. Then we'll select the UsedRange to get the range of cells that have data. Then we'll run that through a ForEach loop, skipping the first 5 rows since they have garbage/header info. For each row we'll make a new object, with properties set to the associated cell (kind of like what you do with all your variables). All of those objects will be collected in an array, which we output to a CSV file. If you don't like the CSV, you could pipe it to Format-Table, and pipe that to Out-File (might have to pipe to out-string, then out-file... it's not something I do often).
$strPath = "C:\Users\User\Documents\EXEL\fj.xls"
$AssetInv = "C:\Users\User\Documents\EXEL\fj.txt"
$objExcel = New-Object -ComObject Excel.Application
$objExcel.Visible = $false
$WorkBook = $objExcel.Workbooks.Open($strPath)
$worksheet = $workbook.sheets.item("Daily Price Quote - Better Of -")
$UsedRange = $worksheet.usedrange
$Data = ForEach($Row in ($UsedRange.Rows|Select -skip 5)){
New-Object PSObject -Property #{
'Site' = $Row.Cells.Item(1).Value2
'City' = $Row.Cells.Item(2).Value2
'State' = $Row.Cells.Item(3).Value2
'Retail Price' = $Row.Cells.Item(18).Value2
'Your Price' = $Row.Cells.Item(20).Value2
'Total Savings' = $Row.Cells.Item(21).Value2
}
}
$Data | Where{[int]::Parse($_.Site) -ge 1} | Select Site,City,State,'Retail Price','Your Price','Total Savings' | Export-Csv -NoTypeInformation -Path $AssetInv
$objExcel.quit()
The plus side is that you also are left with $Data which is all the data you want to be able to use in case you need to do anything else with it (look for items that you save over X%, or items that cost less than $5 or whatever.

Read Excel data with Powershell and write to a variable

Using PowerShell I would like to capture user input, compare the input to data in an Excel spreadsheet and write the data in corresponding cells to a variable. I am fairly new to PowerShell and can't seem to figure this out. Example would be: A user is prompted for a Store Number, they enter "123". The input is then compared to the data in Column A. The data in the corresponding cells is captured and written to a variable, say $GoLiveDate.
Any help would be greatly appreciated.
User input can be read like this:
$num = Read-Host "Store number"
Excel can be handled like this:
$xl = New-Object -COM "Excel.Application"
$xl.Visible = $true
$wb = $xl.Workbooks.Open("C:\path\to\your.xlsx")
$ws = $wb.Sheets.Item(1)
Looking up a value in one column and assigning the corresponding value from another column to a variable could be done like this:
for ($i = 1; $i -le 3; $i++) {
if ( $ws.Cells.Item($i, 1).Value -eq $num ) {
$GoLiveDate = $ws.Cells.Item($i, 2).Value
break
}
}
Don't forget to clean up after you're done:
$wb.Close()
$xl.Quit()
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($xl)
I find it preferable to use an OleDB connection to interact with Excel. It's faster than COM interop and less error prone than import-csv. You can prepare a collection of psobjects (one psobject is one row, each property corresponding to a column) to match your desired target grid and insert it into the Excel file. Similarly, you can insert a DataTable instead of a PSObject collection, but unless you start by retrieving data from some data source, PSObject collection way is usually easier.
Here's a function i use for writing a psobject collection to Excel:
function insert-OLEDBData ($file,$sheet,$ocol) {
{
"xlsb$"
{"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=`"$File`";Extended Properties=`"Excel 12.0;HDR=YES;IMEX=1`";"}
"xlsx$"
{"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=`"$File`";Extended Properties=`"Excel 12.0 Xml;HDR=YES;IMEX=1`";"}
}
$OLEDBCon = New-Object System.Data.OleDb.OleDbConnection($cs)
$hdr = $oCol|gm -MemberType NoteProperty|%{$_.name}
$names = '[' + ($hdr-join"],[") + ']'
$vals = (#("?")*([array]$hdr).length)-join','
$sql = "insert into [$sheet`$] ($names) values ($vals)"
$sqlCmd = New-Object system.Data.OleDb.OleDbCommand($sql)
$sqlCmd.connection = $oledbcon
$cpary = #($null)*([array]$hdr).length
$i=0
[array]$hdr|%{([array]$cpary)[$i] = $sqlCmd.parameters.add($_,"VarChar",255);$i++}
$oledbcon.open()
for ($i=0;$i-lt([array]$ocol).length;$i++)
{
for ($k=0;$k-lt([array]$hdr).length;$k++)
{
([array]$cpary)[$k].value = ([array]$oCol)[$i].(([array]$hdr)[$k])
}
$res = $sqlCmd.ExecuteNonQuery()
}
$OLEDBCon.close()
}
This does not seem to work anymore. I swear it used to, but maybe an update to O365 killed it? or I last used it on Win 7, and have long since moved to Win 10:
$GoLiveDate = $ws.Cells.Item($i, 2).Value
I can still use .Value for writing to a cell, but not for reading it into a variable. instead of the contents of the cell, It returns: "Variant Value (Variant) {get} {set}"
But after some digging, I found this does work to read a cell into a variable:
$GoLiveDate = $ws.Cells.Item($i, 2).Text
In regards to the next question / comment squishy79 asks about slowness, and subsequent
OleDB solutions, I can't seem to get those to work in modern OS' either, but my own performance trick is to have all my Excel PowerShell scripts write to a tab delimited .txt file like so:
Add-Content -Path "C:\FileName.txt" -Value $Header1`t$Header2`t$Header3...
Add-Content -Path "C:\FileName.txt" -Value $Data1`t$Data2`t$Data3...
Add-Content -Path "C:\FileName.txt" -Value $Data4`t$Data5`t$Data6...
then when done writing all the data, open the .txt file using the very slow Com "Excel.Application" just to do formatting then SaveAs .xlsx (See comment by SaveAs):
Function OpenInExcelFormatSaveAsXlsx
{
Param ($FilePath)
If (Test-Path $FilePath)
{
$Excel = New-Object -ComObject Excel.Application
$Excel.Visible = $true
$Workbook = $Excel.Workbooks.Open($FilePath)
$Sheet = $Workbook.ActiveSheet
$UsedRange = $Sheet.UsedRange
$RowMax = ($Sheet.UsedRange.Rows).count
$ColMax = ($Sheet.UsedRange.Columns).count
# This code gets the Alpha character for Columns, even for AA AB, etc.
For ($Col = 1; $Col -le $ColMax; $Col++)
{
$Asc = ""
$Asc1 = ""
$Asc2 = ""
If ($Col -lt 27)
{
$Asc = ([char]($Col + 64))
Write-Host "Asc: $Asc"
}
Else
{
$First = [math]::truncate($Col / 26)
$Second = $Col - ($First * 26)
If ($Second -eq 0)
{
$First = ($First - 1)
$Second = 26
}
$Asc1 = ([char][int]($First + 64))
$Asc2 = ([char][int]($Second + 64))
$Asc = "$Asc1$Asc2"
}
}
Write-Host "Col: $Col"
Write-Host "Asc + 1: $Asc" + "1"
$Range = $Sheet.Range("a1", "$Asc" + "1")
$Range.Select() | Out-Null
$Range.Font.Bold = $true
$Range.Borders.Item(9).LineStyle = 1
$Range.Borders.Item(9).Weight = 2
$UsedRange = $Sheet.UsedRange
$UsedRange.EntireColumn.AutoFit() | Out-Null
$SavePath = $FilePath.Replace(".txt", ".xlsx")
# I found scant documentation, but you need a file format 51 to save a .txt file as .xlsx
$Workbook.SaveAs($SavePath, 51)
$Workbook.Close
$Excel.Quit()
}
Else
{
Write-Host "File Not Found: $FilePath"
}
}
$TextFilePath = "C:\ITUtilities\MyTabDelimitedTextFile.txt"
OpenInExcelFormatSaveAsXlsx -FilePath $TextFilePath
If you don't care about formatting, you can just open the tab delimited .txt files as-is in Excel.
Of course, this is not very good for inserting data into an existing Excel spreadsheet unless you are OK with having the script rewrite the whole sheet it each time an insert is made. It will still run much faster than using COM in most cases.
I found this, and Yevgeniy's answer. I had to do a few minor changes to the above function in order for it to work. Most notably the handeling of NULL or empty valued values in the input array. Here is Yevgeniy's code with a few minor changes:
function insert-OLEDBData {
PARAM (
[Parameter(Mandatory=$True,Position=1)]
[string]$file,
[Parameter(Mandatory=$True,Position=2)]
[string]$sheet,
[Parameter(Mandatory=$True,Position=3)]
[array]$ocol
)
$cs = Switch -regex ($file)
{
"xlsb$"
{"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=`"$File`";Extended Properties=`"Excel 12.0;HDR=YES`";"}
"xlsx$"
{"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=`"$File`";Extended Properties=`"Excel 12.0 Xml;HDR=YES`";"}
}
$OLEDBCon = New-Object System.Data.OleDb.OleDbConnection($cs)
$hdr = $oCol | Get-Member -MemberType NoteProperty,Property | ForEach-Object {$_.name}
$names = '[' + ($hdr -join "],[") + ']'
$vals = (#("?")*([array]$hdr).length) -join ','
$sql = "insert into [$sheet`$] ($names) values ($vals)"
$sqlCmd = New-Object system.Data.OleDb.OleDbCommand($sql)
$sqlCmd.connection = $oledbcon
$cpary = #($null)*([array]$hdr).length
$i=0
[array]$hdr|%{([array]$cpary)[$i] = $sqlCmd.parameters.add($_,"VarChar",255);$i++}
$oledbcon.open()
for ($i=0;$i -lt ([array]$ocol).length;$i++)
{
for ($k=0;$k -lt ([array]$hdr).length;$k++)
{
IF (([array]$oCol)[$i].(([array]$hdr)[$k]) -notlike "") {
([array]$cpary)[$k].value = ([array]$oCol)[$i].(([array]$hdr)[$k])
} ELSE {
([array]$cpary)[$k].value = ""
}
}
$res = $sqlCmd.ExecuteNonQuery()
}
$OLEDBCon.close()
}

Resources