I want to open the CSV file using powershell Excel.Application.
my code is like this:
$csv = "csv name"
$xlsx = "output excel name"
$excel = New-Object -ComObject Excel.Application
$excel.Visible = $false
$wb = $excel.Workbook.Open($csv)
$wb.SaveAs($xlsx,51)
$excel.Quit()
But Turns out that the data in the csv "004" will loaded as 4
Anyone can think of a way to do this?
Noted that there are many special case in my csv:
there are data like "004", "01234678" in the csv and I would like to import all of them as text.
there are comma within the data like "FlatA, 7/F"
there are newline character within the data like
"abcdef
def
ghi"
you can also give your own solution that can load the csv to excel using powershell which can fulfill all the above cases.
Thanks a lot. You will save my life if you able to do this.
Related
I have this excel sheets and I want to have the same format for csv files. Could some one help me with a automation script please (to convert multiple excel sheets to csv files)??
I tried this script, but the 16th digit of the card number is turning to be zero as excel can read only 15 digits right. Can we modify this code to convert multiple excel sheets to csv files?
Could someone help me with this.
Convert Excel file to CSV
$xlCSV=6
$Excelfilename = “C:\Temp\file.xlsx”
$CSVfilename = “C:\Temp\file.csv”
$Excel = New-Object -comobject Excel.Application
$Excel.Visible = $False
$Excel.displayalerts=$False
$Workbook = $Excel.Workbooks.Open($ExcelFileName)
$Workbook.SaveAs($CSVfilename,$xlCSV)
$Excel.Quit()
If(ps excel){kill -name excel}
Excel is really particular in its handling of CSV files..
Although the 16 digit numbers are written out in full when using the SaveAs method, if you re-open it by double-clicking the csv file, Excel screws up these numbers by converting them to numeric values instead of strings.
In order to force Excel to NOT interpret these values and simply regard them as strings, you need to adjust the values in the csv file afterwards, by prefixing them with a TAB character.
(this will make the file useless for other applications..)
Of course, you need to know the correct column header to do this.
Let's assume your Excel file looks like this:
As you can see, the value we need to adjust is stored in column Number
To output csv files on which you can double-click so they are opened in Excel, the code below would do that for you:
$xlCSV = 6
$Excelfiles = 'D:\test.xlsx', 'D:\test2.xlsx' # an array of files to convert
$ColumnName = 'Number' # example, you need to know the column name
# create an Excel COM object
$Excel = New-Object -comobject Excel.Application
$Excel.Visible = $False
$Excel.DisplayAlerts = $False
foreach ($fileName in $Excelfiles) {
$Workbook = $Excel.Workbooks.Open($fileName)
# use the same file name, but change the extension to .csv for output
$CSVfile = [System.IO.Path]::ChangeExtension($fileName, 'csv')
# have Excel save the csv file
$Workbook.SaveAs($CSVfile, $xlCSV)
$Workbook.Close($false)
}
# close excel and clean up the used COM objects
$Excel.Quit()
$null = [System.Runtime.Interopservices.Marshal]::ReleaseComObject($Workbook)
$null = [System.Runtime.Interopservices.Marshal]::ReleaseComObject($Excel)
[System.GC]::Collect()
[System.GC]::WaitForPendingFinalizers()
# now import the csv files just created and update the card number
# column by prefixing the value with a TAB character ("`t").
# this will effectively force Excel NOT to interpret the value as numeric.
# you better not do this inside the same loop, because Excel keeps a lock
# on outputted csv files there.
foreach ($fileName in $Excelfiles) {
# use the same file name, but change the extension to .csv for output
$CSVfile = [System.IO.Path]::ChangeExtension($fileName, 'csv')
# the '-UseCulture' switch makes sure the same delimiter character is used
$csv = Import-Csv -Path $CSVfile -UseCulture
foreach ($item in $csv) { $item.$ColumnName = "`t" + $item.$ColumnName }
# re-save the csv file with updates values
$csv | Export-Csv -Path $CSVfile -UseCulture -NoTypeInformation
}
I have this CSV file I generate using Export-CSV. Everything is fine with it but it display like this when opening in Excel because the cells are not formatted as TEXT:
I want to force open the CSV with the cells all set to TEXT like you can do manually with the interface.
Is there a way to automate that with PowerShell, opening the CSV in Excel with cells formatted as text?
There is a little trick you can use - convert your data to html, and save with "xls" extention. For example:
Get-Process | convertto-html | Out-File csv2.xls
You'll see a warning when opening it, just click OK.
You can suppress that warning message by adding extra key in registry:
open regedit
HKEY_CURRENT_USER\Software\Microsoft\Office\15.0\Excel\Security
Create a new DWORD with name ExtensionHardening and value 0
Found a very good way to make it happen!
After generating your CSV file, here is how to automatically load it into Excel with AutoFit column width and TEXT format for cells :) :
$Fichier = "PATH_TO_CSV.csv"
$objExcel = New-Object -ComObject Excel.Application
$WorkBook = $objExcel.Workbooks.Open($Fichier)
$WorkSheet = $WorkBook.worksheets.item(1)
$objExcel.Visible = $true
$Range = $worksheet.UsedRange.Cells
$range.NumberFormat = "#"
$WorkSheet.Columns("A:B").AutoFit()
I have an Excel file that I receive and want to process it to a CSV using Powershell.
I have to alter it quite specifically so it can be a reliable input for a program that will process the csv info.
I don't know the exact headers, but i know there can be duplicates.
What I do is open the xlsx file with excel and save it as CSV:
$objExcel = New-Object -ComObject Excel.Application
$objExcel.Visible = $True
$objExcel.DisplayAlerts = $True
$Workbook = $objExcel.Workbooks.open($xlsx1)
$WorkSheet = $WorkBook.sheets.item($sheet)
$xlCSV = 6
$Workbook = $objExcel.Workbooks.open($xlsx2)
$WorkSheet = $WorkBook.sheets.item($sheet)
$WorkBook.SaveAs($csv2,$xlCSV)
Now, the XLSX file will have comma's, so first I want to change them to dots.
I tried this, but it's not working:
$objRange = $worksheet.UsedRange
$objRange.Replace ",", "."
It errors out saying: Unexpected token '", "'.
Then when saving I want to set the Delimiter to comma, as it uses ";" standard.
With something like:
$WorkBook.SaveAs($csv2,$xlCSV) -delimiter ","
The last problem is the duplicate headers; this prevents PS to use Import-CSV. Here I tried, when file is separated with a comma it works:
Get-Content $downloads\BBKS_DIR_AUTO_COMMA.csv -totalcount 1 >$downloads\Headers.txt
But then I need to rename de duplicate names like I can have Regio, Regio, Regio.
I want to change this to Regio, Regio2, Regio3
My plan was to lookup the data of the txt, search for duplicates, and then ad an incremental nummer.
In the end I need to add a column with incremental numbers, but always with four numbers, like; 0001, 0002, 0010, 0020, 0200, 1500, I wont exceed 9999. How can this be done?
If you can help me, if only partially I'm very happy.
Further, I'm running Windows 7 x64, Powershell 3.0, Excel 2016 (if relevant)
If easier, its fine to go back to Command prompt for some tasks.
Personally, I wouldn't try and work with Excel sheets via Excel itself and COM - I'd use the excellent module https://github.com/dfinke/ImportExcel
Then you can import from the sheet straight to a native Powershell object array, and re-export with Export-Csv -Delimiter.
Edit: To answer follow ups :
Once you've loaded the module you can do "Get-Module ImportExcel | Select-Object -ExpandProperty ExportedCommands" to see what it makes available.
To import your Excel in the first place, do something like :
$WorkBook = Import-Excel
And if you need to take care of duplicate column names, you can do :
$WorkBook = Import-Excel -Header #("Regio1", "Regio2", "Regio")
Where the array you pass to -Header needs to include every column you want from the workbook.
I am doing data output to csv file via powershell. Generally things goes well.
I have exported the data to csv file. It contains about 10 columns. When I open it with MS Excel it's all contained in first column. I want to split it by several columns programmatically via powershell(same GUI version offers). I could make looping and stuff to split the every row and then put values to appropriate cell but then it would take way too much time.
I believe there should be an elegant solution to make one column split to multiple. Is there a way to make it in one simple step without looping?
This is what I came up with so far:
PS, The CSV file is 100% FINE. The delimiter is ','
Get-Service | Export-Csv -NoTypeInformation c:\1.csv -Encoding UTF8
$xl = New-Object -comobject Excel.Application
$xl.Visible = $true
$xl.DisplayAlerts = $False
$wb = $xl.Workbooks.Open('c:\1.csv')
$ws = $wb.Sheets|?{$_.name -eq '1'}
$ws.Activate()
$col = $ws.Cells.Item(1,1).EntireColumn
This will get you the desired functionality; add to your code. Check out the MSDN page for more information on TextToColumns.
# Select column
$columnA = $ws.Range("A1").EntireColumn
# Enumerations
$xlDelimited = 1
$xlTextQualifier = 1
# Convert Text To Columns
$columnA.texttocolumns($ws.Range("A1"),$xlDelimited,$xlTextQualifier,$true,$false,$false,$true,$false)
$ws.columns.autofit()
I had to create a CSV which had "","" as delimiter to test this out. The file with "," was fine in excel.
# Opens with all fields in column A, used to test TextToColumns works
"Name,""field1"",""field2"",""field3"""
"Test,""field1"",""field.2[]"",""field3"""
# Opens fine in Excel
Name,"field1","field2","field3"
Test,"field1","field.2[]","field3"
Disclaimer: Tested with $ws = $wb.Worksheets.item(1)
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.