Import csv to excel using powershell - excel

I'm trying to import a .txt file which is comma-separated. It gets imported. But excel doesn't seem to understand that it is, comma-separated. It displays all in the same column.
[threading.thread]::CurrentThread.CurrentCulture = 'en-US'
$wbpath=Join-Path "$psscriptroot" 'file.xlsx'
$importcsv=Join-Path "$psscriptroot" 'file.txt'
$xl = New-Object -ComObject Excel.Application
$xl.Visible = $false
$xl.Workbooks.OpenText($importcsv)
$xl.DisplayAlerts = $false
[threading.thread]::CurrentThread.CurrentCulture = 'en-US'
$xl.ActiveWorkbook.SaveAs($wbpath,51)
$xl.Quit()
Any suggestions? Thanks.

You have two options. One, if your file extension is .csv instead of .txt, it would work as is. The second option, make sure you pass $True for the comma-delimiter parameter, like so:
$xl.Workbooks.OpenText($importcsv, 2, 1, 1, 1, $False, $False, $False, $True)

You need to supply more parameters to the OpenText method to get it to see the delimiter.
$wbpath=Join-Path "$psscriptroot" 'file.xlsx'
$importcsv=Join-Path "$psscriptroot" 'file.txt'
$xl = New-Object -ComObject Excel.Application
$xl.Visible = $true
$xlWindows=2
$xlDelimited=1
$xlTextQualifierDoubleQuote=1
$StartRow=1
$xl.workbooks.OpenText($importcsv,$xlWindows,$StartRow,$xlDelimited,$xlTextQualifierDoubleQuote,$false,$false,$false,$true)
$xl.ActiveWorkbook.SaveAs($wbpath,51)
$xl.Quit()
See the MSDN reference for full details:
https://msdn.microsoft.com/en-us/library/office/ff837097.aspx
The first $false tells it not to consider consecutive delimiters as one, the next one tells it not to consider Tab as a delimiter, the next $false does the same for semicolon, and the $true tells it to use comma as a delimiter. There are additional delimiter options after that that I have not included as the delimiters are all optional, and you only have to include parameters up to the last relevant one to your needs (setting comma to $true).

Related

Load variable data into a workbook using PowerShell

I have an API request that set a variable named $data with CSV style data.
I want to open a Workbook with that data without writing on disk.
How can I do that?
The best I can do is
$excel = New-Object -ComObject excel.application
$workbook = $excel.Workbooks.Add()
$workbook.worksheets(1).Cells(1,1) = $csv
Unfortunately, it fills my CSV into 1 cell, adding delimiter, instead of simply "copying" data into the workbook.
This is a fairly simple task if you want to use the ComObject, as you can use ConvertTo-Csv with a tab delimiter, copy to the clipboard, and paste into Excel. Here's a snippet of what I've used in a script myself to do just that:
$tasks|ConvertTo-Csv -del "`t" -NoTypeInformation|clip
$XL = New-Object -ComObject Excel.Application
$XL.Visible = $true
$WB = $XL.Workbooks.Add()
$XL.ActiveCell.PasteSpecial() | Out-Null

Using Powershell to convert text to number in Excel

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.

How do I embed hyperlinks from one excel file into text from another excel file with powershell

Good Evening everyone,
I have a problem that I am having some issues with and I really need some help. I took two csv files and compared them and converted them to an xls. Now the part I am confused about is how will I be able to take the hyperlinks from Column 1, Row 1 in one excel document and embed them into the text in the other document Column 1, Row2.
is there an easy way to do this? I found the follow link which left me a little confused : https://social.technet.microsoft.com/Forums/scriptcenter/en-US/123d673a-f9a7-4ae6-ae9c-d4ae8ef65015/powershell-excel-how-do-i-create-a-hyperlink-to-a-cell-in-another-sheet-of-the-document?forum=ITCG
I appreciate any guidance and help you can offer.
#Define the file path and sheet name
$FilePath= `enter
code"C:\Users\cobre\Desktop\PowerShell\HomeWork2\Test3.csv"
$FilePath2="C:\Users\cobre\Desktop\PowerShell\HomeWork2\Test3.xls"
$FilePath3="C:\Users\cobre\Desktop\PowerShell\HomeWork2\Test4.xls"
$SheetName="Test3"
$SheetName2="HyperLinks"
#Compare two CSV files to look for matches
$CSV1 = import-csv -path
C:\Users\cobre\Desktop\PowerShell\HomeWork2\Test1.csv
$CSV2 = import-csv -path
C:\Users\cobre\Desktop\PowerShell\HomeWork2\Test2.csv
Compare-Object $CSV1 $CSV2 -property ShoppingList -IncludeEqual | where-
object {$_.SideIndicator -eq "=="}
# Create an Object Excel.Application using Com interface
$objExcel = New-Object -ComObject Excel.Application
# Enable the 'visible' property so the document will open in excel
$objExcel.Visible = $true
$objExcel.DisplayAlerts = $False
# Open the Excel file and save it in $WorkBook
$WorkBook = $objExcel.Workbooks.Open($FilePath)
# Load the WorkSheet "Test3"
$WorkSheet = $WorkBook.sheets.item($SheetName)
# Delete data from column
[void]$WorkSheet.Cells.Item(1,2).EntireColumn.Delete()
#Auto fit everything so it looks better
$usedRange = $WorkSheet.UsedRange
$usedRange.EntireColumn.AutoFit() | Out-Null
#Save and convert to XLS
$Workbook.SaveAs("C:\Users\cobre\Desktop\PowerShell\HomeWork2\Test3.xls",1)
$Workbook.Saved = $True
#Load
$excel = New-Object -comobject Excel.Application
$excel.Visible = $True
$workbook = $objExcel.Workbooks.Add()
$workbook.Worksheets.Item($FilePath2).Hyperlinks.Add( `
$workbook.Worksheets.Item($FilePath2).Cells.Item(1,2) , `
"" , $FilePath3, "https://community.spiceworks.com/topic/673034-powers
You can use something like this:
$excel = New-Object -comobject Excel.Application
$excel.Visible = $True
$workbook = $excel.Workbooks.Add()
$workbook.Worksheets.Item(1).Hyperlinks.Add($workbook.Worksheets.Item(1).Cells.Item(1,1) ,"" , "Sheet2!C4", "", "Link to sheet2")
Reference : Hyperlinks.Add Method
Hope it helps

Excel functions in powershell

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++
)

Importing CSV Into New Worksheet

I'm trying to import a CSV file into a newly created Excel worksheet, but haven't been able to utilize existing Q&A here (and elsewhere) to solve this issue.
Also, I'm sure I'm making this WAY more difficult than it should be, so please feel free to correct this bloated code if you see fit:
$varOneSheet = "OneSheet"
$xlsNewFile = New-Object -ComObject Excel.Application
$xlsNewFile.SheetsInNewWorkbook = 3
$xlsNewFile.displayAlerts = $false
$xlsNewFile.Visible = $false
$xlsWorkbook = $xlsNewFile.Workbooks.Add()
$sheetToRename = $xlsNewFile.Sheets.Item("Sheet1")
$sheetToRename.Name = $OneSheet
#this all works below, we need to push the data over to #xlsWorkbook now
$xlsCSVFile = New-Object -ComObject Excel.Application
$xlsCSVFile.displayAlerts = $false
$csvFilename = (".\DATA.CSV")
$xlsCSVFile.Workbooks.OpenText($csvFilename, 2, 1, 1, 1, $false, $false, $false, $true)
$xlsCSVFile.Visible = $true
$tmpSheetTOFile = $xlsWorkbook.Sheets.Item(1)
$tmpWorksheet = $xlsCSVFile.Sheets.Item(1)
#########################above is fine
#########################below should copy into $xlsWorkbook Sheet 1
$tmpWorksheet.Copy($tmpSheetTOFile)
The last line above is the failure point, which yields:
Exception calling "Copy" with "1" argument(s): "Copy method of Worksheet class
failed"
At line:1 char:23
+ $tmpWorksheet.Copy <<<< ($tmpSheetTOFile)
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : ComMethodTargetInvocation
Do I really need to create a separate/temporary workbook? Why was I not able to simply use OpenText on the already Saved/existing Workbook?
EDIT: I used this previous question to get to where I am now, so that's why I'm uncertain as to where the failure point lies. As the answer was accepted and signed-off on.
You're creating two different Excel application instances:
$xlsNewFile = New-Object -ComObject Excel.Application
...
$xlsCSVFile = New-Object -ComObject Excel.Application
Copying only works within the same instance, and using two instances isn't required anyway. Simply remove
$xlsCSVFile = New-Object -ComObject Excel.Application
$xlsCSVFile.displayAlerts = $false
...
$xlsCSVFile.Visible = $true
and change
$xlsCSVFile.Workbooks.OpenText($csvFilename, 2, 1, 1, 1, $false, $false, $false, $true)
...
$tmpWorksheet = $xlsCSVFile.Sheets.Item(1)
...
$tmpWorksheet.Copy($tmpSheetTOFile)
to
$xlsNewFile.Workbooks.OpenText($csvFilename, 2, 1, 1, 1, $false, $false, $false, $true)
...
$xlsNewFile.Workbooks.Item(2).Sheets.Item(1).Copy($tmpSheetTOFile)
Having that said, Excel auto-creates a workbook with a new sheet when it imports a CSV anyway (which is also the reason why OpenText doesn't import a CSV into an existing workbook), so why do you need to copy it to another new workbook in the first place? Normally it would suffice to just save the imported CSV as an Excel workbook. If you require additional sheets you can just add them.
$wsName = 'OneSheet'
$csvFilename = '.\data.csv'
$xlsFilename = '.\data.xlsx'
$xl = New-Object -ComObject 'Excel.Application'
$xl.DisplayAlerts = $false
$xl.Visible = $false
$xl.Workbooks.OpenText($csvFilename, 2, 1, 1, 1, $false, $false, $false, $true)
$wb = $xl.Workbooks.Item(1)
$ws = $wb.Sheets.Item(1)
$ws2 = $wb.Sheets.Add([Type]::Missing, $ws)
$ws3 = $wb.Sheets.Add([Type]::Missing, $ws2)
$ws.Name = $wsName
$wb.SaveAs($xlsFilename, 51)

Resources