Convert txt to xlsx

This topic contains 7 replies, has 5 voices, and was last updated by Profile photo of Curtis Smith Curtis Smith 2 months, 1 week ago.

  • Author
  • #25254
    Profile photo of PowerShell84

    hi developer,

    I want to convert a text file into an xlsx file. here i use following powershell script.

    Get-Content .\aa.txt | Foreach-Object {($_ -replace "\s+",",")}|Out-File -FilePath [b]converted.csv[/b] -Encoding OEM 

    The script works as above but i am going to change to xlsx in Out-File.

    Get-Content .\aa.txt | Foreach-Object {($_ -replace "\s+",",")}|Out-File -FilePath [b]converted.xlsx[/b] -Encoding OEM 

    it does not working

    how to convert txt to xlsx and worksheet name?
    Any Idea?


  • #25262
    Profile photo of Don Jones
    Don Jones

    Out-File produces text files. It doesn't matter what filename extension you give it, it's always a text file. Excel files are not text files.

    Try Export-CSV instead of Out-File. That will produce a CSV file, which Excel can open.

  • #25263
    Profile photo of Rob Simmers
    Rob Simmers

    You have a text file, which looks like it's space delimited?

    computer1 rob laptop
    computer3 john desktop
    computer4 sam laptop

    You would want to define the header row by creating a PSObject and as Don says above, Export-CSV. There are multiple ways to do things, but without seeing the file all we can do is provide an example:

    #Grab the text file
    $textFile = Get-Content 'C:\Users\rsimmers\Desktop\test.txt'
    #Loop through each line and assign everything produced in the
    $result = foreach ($line in $textFile) {
        #Split the line into an array using space as a delimiter
        $array = $line -Split " "
        #Create a new object to return to $result and define the what each "column" would be assigned to
        New-Object -TypeName PSObject -Property @{ComputerName=$array[0];Owner=$array[1];Type=$array[2]}
    #Export the object to a CSV
    $result | Export-CSV C:\Test\MyCSV.csv -NoTypeInformation
  • #25297
    Profile photo of PowerShell84

    I want convert Txt file to [u][i]XLSX[/i][/u] not [b]CSV[/b]

  • #25298
    Profile photo of Don Jones
    Don Jones

    Powershell doesn't do that.

  • #25305
    Profile photo of Don Jones
    Don Jones

    Have a look at If you can import your text file and get the data into object form, Doug's tool will help you get it into an actual Excel file.

  • #50306
    Profile photo of Santhosh Rao
    Santhosh Rao

    The above link is broken, can you share an other one.

  • #50313
    Profile photo of Curtis Smith
    Curtis Smith

You must be logged in to reply to this topic.