Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Imported .csv file with formulas

I have imported a comma seperated csv file using powershell. I gets imported and looks as it should. The problem is, the cells contain formulas. Like =20+50+70. It doesn't get calculated unless i click enter i the top field. Another problem is, that some of the cells contains numbers like =50,2+70,5. These cells excel doesn't understand at all. It can't caltulate them, unless i remove the , or replace it with a dot (.). But this is not a possibility. How to i fix this? The csv file is imported with powershell using this:

[threading.thread]::CurrentThread.CurrentCulture = 'en-US'
$wbpath=Join-Path "$psscriptroot" 'file.xlsx'
$importcsv=Join-Path "$psscriptroot" 'file.csv'
$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()
while([System.Runtime.Interopservices.Marshal]::ReleaseComObject($xl)){'released'}

The

[threading.thread]::CurrentThread.CurrentCulture = 'en-US'

is necessary or i will get errors because my system locale is not us.

Thank you.

CSV Sample:

name1.name1.name1,"=20","=7,65","=20,01"
name2.name2.name2,"=20+10","=4,96+0,65","=20,01+10"
name3.name3.name3,"=20","=4,96+0,88","=21,01+11"
like image 901
user3019059 Avatar asked Oct 31 '22 09:10

user3019059


1 Answers

Sounds like you need to

a) Force the worksheet to calculate

b) If you're going to stick with en-US locale then you need to replace those commas with decimal points. That's the GB/US standard and how Excel will interpret decimals. I'd strongly advise however that you stick to the locale that your data is set up in.

(untested as I'm currently on a Mac)

[threading.thread]::CurrentThread.CurrentCulture = 'en-US'
$wbpath=Join-Path "$psscriptroot" 'file.xlsx'
$importcsv=Join-Path "$psscriptroot" 'file.csv'
$xl = New-Object -ComObject Excel.Application
$xl.Visible = $false
$wb = $xl.Workbooks.OpenText($importcsv)
$xl.DisplayAlerts = $false
[threading.thread]::CurrentThread.CurrentCulture = 'en-US'
$sh = $wb.Sheets.Item(1)
# loop through the used range and replace any commas with decimals
foreach ($cell in $sh.usedRange)
{
    [string]$formula = $cell.formula
    $formula -replace ',','.'
    $cell.formula = $formula
}
# force the sheet to calculate
$sh.Calculate()
$xl.ActiveWorkbook.SaveAs($wbpath,51)
$xl.Quit()
while([System.Runtime.Interopservices.Marshal]::ReleaseComObject($xl)){'released'}
like image 78
SierraOscar Avatar answered Nov 15 '22 06:11

SierraOscar