1

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.

2 Answers 2

3

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)
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you. All solutions worked. I choose to just rename the file to .csv.
2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.