I have an excel file that has three columns that are set to Number. However, when I open the file I have the this :
I found a helpful link here: stackoverflow link
I have tried this method but I am getting the following error. Is there something I am doing wrong:
$wb = 'C:\Users\user1\Documents\Working Folder\239\239_uploadFile.xlsx'
$excel = new-object -ComObject excel.application
$excel.visible = $false
$excel.DisplayAlerts = $false
$wb = $excel.workbooks.open($wb)
$ws1 = $wb.worksheets.item(3)
$ws1.columns.item(1).numberformat = 0
$ws1.Columns.item(14).Value = $ws1.Columns.item(14).Value
$wb.Save()
$wb.close()
$excel.Quit()
[System.Runtime.InteropServices.Marshal]::ReleaseComObject($excel)
Remove-Variable excel`
[
In recent versions of Excel (as of at least Excel 2019), the .Value property is now a parameterized property and therefore requires an argument in order to be used.
A simple workaround is to use the .Value2 property instead - shown below.
However, .Value2 differs from .Value in that "it doesn’t use the Currency and Date data types" - if those types are required, use .Value(10) (sic) instead (10 is the value of the xlRangeValueDefault constant).
While using the .Item() method explicitly used to be required in earlier PowerShell (Core) versions, this no longer the case as of (at least) PowerShell (Core) 7.2.1.
Therefore, try the following:
& {
$wb = 'C:\Users\user1\Documents\Working Folder\239\239_uploadFile.xlsx'
$excel = new-object -ComObject excel.application
$wb = $excel.workbooks.open($wb)
$ws1 = $wb.worksheets(3)
$ws1.columns(1).numberformat = 0
# Note the use of .Value2, not .Value
$ws1.Columns(14).Value2 = $ws1.Columns(14).Value2
$wb.Save()
$wb.close()
$excel.Quit()
}
Note the use of & { ... }, i.e. the execution of the Excel-related code in a child scope. This makes the calls to and Remove-Variable excel unnecessary - see this answer for more information.
Related
I am using the following code to paste values from one sheet to another. It used to work but after migrating to EXCEL 2013 stopped working with error "Unable to get the Paste property of the Worksheet class"
$excelFrom = New-Object -ComObject Excel.Application
$excelFrom.visible = $false
$excelFrom.DisplayAlerts = $false
$excelTo = New-Object -ComObject Excel.Application
$excelTo.visible = $false
$excelTo.DisplayAlerts = $false
$excelFrom.Workbooks.OpenText("inputfile.xls")
$worksheetFrom = $excelFrom.Worksheets.Item(1)
$excelTo.Workbooks.OpenText("templatefile.xlsx")
$worksheetTo = $excelTo.Worksheets.Item(1)
write-host $worksheetTo.cells[1][2].text
$lastRow1 = $worksheetFrom.UsedRange.rows.count - 11
$lastRow2 = $lastRow1 + 1
#copy account numbers
$worksheetFrom.activate()
$range1 = $worksheetFrom.Range("B15:B17")
$range1.copy()
$worksheetTo.activate()
$range2 = $worksheetTo.Range("A2:A4")
write-host $range2.rows.count
$worksheetTo.Paste($range2)
$excelFrom.quit()
while([System.Runtime.Interopservices.Marshal]::ReleaseComObject($excelFrom)){}
Remove-Variable excelFrom
$excelTo.quit()
while([System.Runtime.Interopservices.Marshal]::ReleaseComObject($excelTo)){}
Remove-Variable excelTo
If it helps anyone I had to use this -
$worksheetTo.Range("A2:A$lastRow2").Value2 = $worksheetFrom.Range("B15:B$lastRow1").Value2
It seems .Value doesn't work if we are copying from an xls file to xlsx –
I have a script that allows me to iterate over every cell (even the unused ones), but when I set the text property of the cell to remove new lines with nothing, I get an error that I can't update all cells even though the script is only updating one cell at a time:
$Excel = New-Object -ComObject Excel.Application
$Excel.Visible = $false
$workbook = $Excel.Workbooks.Open("D:\Excel\excel.xlxs")
$worksheet = $Workbook.Sheets.Item(1)
$allcells = $worksheet.UsedRange.Cells
$total = $allcells.columns.count
$everycell = $worksheet.Range("1:$total")
foreach ($cell in $everycell)
{
if ($cell.Text -ne "")
{
$cell.Text = $cell.Text.Replace("`r`n","")
}
}
$workbook.Save()
$excel.Quit()
To iterate over used cells within a range and remove characters from the cells (in this case a new line), is there a different way to replace all characters in all cells text equal to something else? The manual way of doing this would be to load Excel, and use control and h key to just replace. I would think there's a way to do this as well with the com object.
In my testing, $worksheet.Range("1:$total") was 49152 cells. Here is what I used to simplify removing newlines from each used cell.
$Excel = New-Object -ComObject Excel.Application
$Excel.Visible = $false
$workbook = $Excel.Workbooks.Open("D:\Excel\excel.xlsx")
$worksheet = $Workbook.Sheets.Item(1)
$allcells = $worksheet.UsedRange.Cells
foreach($cell in $allcells)
{
$cell.value = $cell.value2 -replace '\r?\n'
}
$workbook.Save()
$excel.Quit()
Couple of things I wanted to point out. First, you have a typo in the excel filename, maybe that is just in this posting. Second, text is a read only field, you need to set value as shown.
I am new to Powershell and I need to parse text file into excel and edit content.
I managed to open file with the following script:
$Excel = New-Object -ComObject Excel.Application
$Excel.Visible = $true
$Excel.DisplayAlerts = $false
$Excel.Workbooks.OpenText( "Documents\myfile.txt")
It runs without exception, but the data I'm left with tells me the file is not loaded properly.
I need to set parameters like FieldInfo for export.
How do I do this?
Thanks for help.
You have to get the item from the file in order to load it in excel.
DO like this:
$excel = new-object -comobject excel.application
$file = get-item "E:\myfile.txt" # Mention the path of the file
$excel.Visible=$true
$excel.displayalerts = $False
$wb = $excel.workbooks.open($file)
Hope it helps you.
When you bring data into Excel via text file or manual input, Excel will try to interpret what type of data it is, text, date or number. You are bringing in text that looks like a number to Excel.
One solution is to make Powershell do all the work, get it to load the file and then loop through each row. You can then force the format before loading the data.
Something like this:
$Excel = New-Object -ComObject Excel.Application
$Excel.Visible = $true
$wb = $Excel.Workbooks.add()
$ws = $wb.Worksheets[1]
Import-Csv "Documents\myfile.txt" | % {$i = 1}{
$ws.Range("A" + $i).NumberFormat = '#'
$ws.Range("A" + $i).Value = $_.Field1
#Repeat for each field
$i++
)
I need to run a script that just opens an excel file, calculates an excel cell connected with a Pi DataLink, then tells me the value.
If I try to do that in the way that's standard:
$objExcel = New-Object -com Excel.Application
$objExcel.Visible = $True
$WorkBook = $objExcel.Workbooks.Open("C:\Users\crclayton\sheet.xlsx")
$WorkSheet = $WorkBook.Sheets.Item("Sheet1")
write-host $worksheet.Range("A1").Text
$WorkBook.Save()
$WorkBook.Close()
$objExcel.Quit()
I get a #NAME? error. And even if I just use the first three lines to just open an excel file and look at it, I can't run calculations, =PICurrVal("TAGNAME",0,"SERVERNAME") is just a dead formula that excel doesn't understand if I open it this way. I've also tried to UpdateLinks when I open the file, but no dice.
However, if I open the file like so:
Invoke-Item "C:\Users\crclayton\sheet.xlsx"
I don't get a #NAME? error and I can run the calculations and excel understands this formula.
Maybe something like this?
Invoke-Item "C:\Program Files (x86)\Microsoft Office\Office14\EXCEL.EXE"
Start-Sleep 10
$objExcel = Get-Process "EXCEL.EXE"
$WorkBook = $objExcel.Workbooks.Open("C:\Users\crclayton\sheet.xlsx")
$WorkSheet = $WorkBook.Sheets.Item("Sheet1")
write-host $worksheet.Range("A1").Text
Is there some way to get the value in cell A1 having opened the spreadsheet using Invoke-Item?
I'm not sure why you're getting #NAME? as Excel should be doing all the calculations within the sheet all we're doing in Powershell is getting the value of the cell.
However what you can try is outputting the value of your formula to a nearby cell and getting the value of it instead, for example:
Your formula is in D18 -> =PICurrVal("TAGNAME",0,"SERVERNAME")
Your value is in D19 -> =D18
Call the value in your Powershell:
$objExcel = New-Object -com Excel.Application
$objExcel.Visible = $True
$WorkBook = $objExcel.Workbooks.Open("C:\Users\crclayton\sheet.xlsx")
$WorkSheet = $WorkBook.Sheets.Item(1)
write-host $worksheet.Range("D18").Text
$WorkBook.Save()
$WorkBook.Close()
$objExcel.Quit()
Update
Excel addins can be added in powershell by using the Addins property like so:
$MyAddin = $Workbook.AddIns.Add('C:\test.xla', $True)
$MyAddin.Installed = "True"
Your new complete code might look something like
$objExcel = New-Object -com Excel.Application
$objExcel.Visible = $True
$WorkBook = $objExcel.Workbooks.Open("C:\Users\crclayton\sheet.xlsx")
$MyAddin = $Workbook.AddIns.Add('C:\test.xla', $True)
$MyAddin.Installed = "True"
$WorkSheet = $WorkBook.Sheets.Item(1)
write-host $worksheet.Range("D18").Text
$WorkBook.Save()
$WorkBook.Close()
$objExcel.Quit()
Edit 2:
Yes, add-ins were the problem. I needed to add each the following files:
$ExcelAddin = $WorkBook.Application.AddIns.Add("C:\Program Files (x86)\PIPC\Excel\PITrendXL.xla", $True)
$ExcelAddin.Installed = "True"
$ExcelAddin = $WorkBook.Application.AddIns.Add("C:\Program Files (x86)\PIPC\Excel\pipc32.xll", $True)
$ExcelAddin.Installed = "True"
$ExcelAddin = $WorkBook.Application.AddIns.Add("C:\Program Files (x86)\PIPC\Excel\OSIsoft.PIDataLink.UI.dll.manifest", $True)
$ExcelAddin.Installed = "True"
Hi I'm using a simple Powershell script to convert CSV files to XLSX files. However Excel ignores the list seperator and puts all data in the first column.
The list seperator is configured correctly (Start > Control Panel > Regional and Language Options -> Additional Settings)
Manually opening the files from Windows Explorer works fine.
However, when opening the CSV in Excel using:
Function Convert-toExcel {
$xl = new-object -comobject excel.application
$xl.visible = $true
$Workbook = $xl.workbooks.OpenText("$csvfile")
$Worksheets = $Workbooks.worksheets
}
Everything is put into the first column...
Accoriding to Powershell the list seperator is configured correctly:
(Get-Culture).textinfo
ListSeparator : ,
Try adding the DataType argument to the OpenText method. It appears to take magic arguments.
VBA:
Workbooks.OpenText filename:="DATA.TXT", dataType:=xlDelimited, tab:=True
I would guess in powershell it accepts a hash, so:
$xl.Workbooks.OpenText(#{Filename = $CSVFile; dataTyype = "xlDelimited", other = $true; otherchar=':' })
However, I've no way to test this currently.
The following script works for me. The one change in functionality I made was that I set Excel.visible to false.
Function Export-CSVToXLS {
Param(
[String]$CsvFileLocation
,[String]$ExcelFilePath
)
If (Test-Path $ExcelFilePath )
{
Remove-Item -Path $ExcelFilePath
}
$FixedFormat = [Microsoft.Office.Interop.Excel.XlFileFormat]::xlWorkbookDefault
$Excel = New-Object -ComObject excel.application
$Excel.visible = $false
$Excel.Workbooks.OpenText($CsvFileLocation)
$Excel.ActiveWorkbook.SaveAs($ExcelFilePath,$FixedFormat)
$Excel.Quit()
Remove-Variable -Name Excel
[gc]::collect()
[gc]::WaitForPendingFinalizers()
}
Export-CSVToXLS -CsvFileLocation "C:\Temp\CSV.csv" -ExcelFilePath "C:\Temp\XLS.xlsx"
I compiled this based off of information on the following webpages:
http://blogs.technet.com/b/heyscriptingguy/archive/2010/09/09/copy-csv-columns-to-an-excel-spreadsheet-by-using-powershell.aspx
https://social.technet.microsoft.com/Forums/en-US/919459dc-3bce-4242-bf6b-fdf37de9ae18/powershell-will-not-save-excel-file?forum=winserverpowershell
Your original code works fine. My guess is your delimiter in excel just isn't a ",". I've seen this go wrong loads of time. The ps culture has nothing to do with it
Use `t (Powershell code for the tab character) instead of , (a comma).
Excel defaults at opening to using text to columns import with tab as the separator.