Convert CSV to XLSX via PowerShell
A nifty PowerShell script that will take a delimited CSV file and convert it to a XLSX file.
Having extracted data from a substantial database, I was left with a massive delimited CSV file that required conversion to Microsoft Excel XLSX format.

I wanted to save the file as an XLSX and perform a text-to-columns function, thus combining two steps into one.
Thankfully this is possible using PowerShell.

There are several pieces of code online that purport to do this but don’t work well (Example 1, Example 2, Example 3). Online tools exist too (Example 1, Example 2).
The following code is substantially based on the work of Nixta but I have made several changes including the manual specification of the delimiting character. The original code was unable to determine the delimiting character within the CSV and so whilst I was successful in obtaining a XLSX file, it was still semi-colon separated.
The following script will open the specified CSV, save it as an XLSX file to a specified location and perform a text-to-columns based on the delimiter being a semicolon (;). Cells will be in the “General” format.
#Define locations and delimiter
$csv = "c:/path/to/file/whatever.csv" #Location of the source file
$xlsx = "c:/path/to/file/whatever.xlsx" #Desired location of output
$delimiter = ";" #Specify the delimiter used in the file
# Create a new Excel workbook with one empty sheet
$excel = New-Object -ComObject excel.application
$workbook = $excel.Workbooks.Add(1)
$worksheet = $workbook.worksheets.Item(1)
# Build the QueryTables.Add command and reformat the data
$TxtConnector = ("TEXT;" + $csv)
$Connector = $worksheet.QueryTables.add($TxtConnector,$worksheet.Range("A1"))
$query = $worksheet.QueryTables.item($Connector.name)
$query.TextFileOtherDelimiter = $delimiter
$query.TextFileParseType = 1
$query.TextFileColumnDataTypes = ,1 * $worksheet.Cells.Columns.Count
$query.AdjustColumnWidth = 1
# Execute & delete the import query
$query.Refresh()
$query.Delete()
# Save & close the Workbook as XLSX.
$Workbook.SaveAs($xlsx,51)
$excel.Quit()
Comments
51 responses to “Convert CSV to XLSX via PowerShell”
Good work!
Very useful, it works exactly as described, thanks!
How would i go about changing the encoding in the output of this script? I have csv’s containing ÅÄÖ, which turns to gibberish when i run this otherwise excellent script.
Just add
$query.TextFilePlatform = 65001
worked for me
You are gorgeous, million Thanks
Thanks for this, while my files are converting here’s an addition to the above script (for converting all CSV files in a folder)
gci "c:/path/to/find/files/*.csv" | %{
$Path = $_.DirectoryName
$filename = $_.BaseName
#Define locations and delimiter
$csv = $_.FullName #Location of the source file
#$xlsx = "$Path/$filename.xlsx" # Names & saves Excel file same name/location as CSV
$xlsx = "c:/path/to/save/files/$filename.xlsx" # Names Excel file same name as CSV
$delimiter = ";" #Specify the delimiter used in the file
# Create a new Excel workbook with one empty sheet
$excel = New-Object -ComObject excel.application
$workbook = $excel.Workbooks.Add(1)
$worksheet = $workbook.worksheets.Item(1)
# Build the QueryTables.Add command and reformat the data
$TxtConnector = ("TEXT;" + $csv)
$Connector = $worksheet.QueryTables.add($TxtConnector,$worksheet.Range("A1"))
$query = $worksheet.QueryTables.item($Connector.name)
$query.TextFileOtherDelimiter = $delimiter
$query.TextFileParseType = 1
$query.TextFileColumnDataTypes = ,1 * $worksheet.Cells.Columns.Count
$query.AdjustColumnWidth = 1
# Execute & delete the import query
$query.Refresh()
$query.Delete()
# Save & close the Workbook as XLSX.
$Workbook.SaveAs($xlsx,51)
$excel.Quit()
}
Very nice and usefull but can you explain to me what the next three lines of code should be doing?
$query.TextFileParseType = 1
$query.TextFileColumnDataTypes = ,1 * $worksheet.Cells.Columns.Count
$query.AdjustColumnWidth = 1
When i rule them out the created xlsx is still the same.
Greatings..
In this sample code, the Cells are in the “General” format. How do I change it to “Text” format?
Change
TextFileColumnDataTypes
from 1 to 2I would like to delete the file in the the folder where the csv is locate at the end of the convertion. Can you help me
wow google for two minutes should have brought you an answer.
Just add these lines at the end of the code:
if($?)
{
Remove-Item $csv
}
the last 2 lines
# Save & close the Workbook as XLSX.
$Workbook.SaveAs($xlsx,51)
$excel.Quit()
save the file in excel format. if for example the file exists and you want to overwrite it how do you overwrite it?
You can overwrite by adding this:
$excel.DisplayAlerts = $False
Hi, I tried to using this csv to Excel convert in one of storage Capacity reporting script. In script the storage cmd will run and generate a CSV data and I tried to put it as source for this script. It is working successfully when I manually running it. But the xlsx file is not generating when I putting this in a Windows task scheduler and running it , but storage cmd and csv file generation is happening. Could you someone help me on where is wrong. I am confused.
Below is the script:-
Excel needs to be registered as an interactive user in DCOM for automation to work. The following articles helped me with this problem:
https://stackoverflow.com/questions/22062284/server-execution-failed-exception-from-hresult-0x80080005-co-e-server-exec-fa/39725040#39725040
https://blogs.technet.microsoft.com/the_microsoft_excel_support_team_blog/2012/11/12/microsoft-excel-or-microsoft-word-does-not-appear-in-dcom-configuration-snap-in/
Hi guys,
the script is working great but I don’t understand what means the $Workbook.SaveAs($xlsx,51) 51?
What is this for? and why is the script gcreating an xlsx in Documents?
Any help appriciated
Olaf
It is for the filetype. Just look at these articles from msdn:
https://msdn.microsoft.com/de-de/vba/excel-vba/articles/xlfileformat-enumeration-excel
https://msdn.microsoft.com/en-us/vba/excel-vba/articles/workbook-saveas-method-excel
51 is the code for open xml *.xlsx format
It worked! Ty.
Any idea how i could treat consecutive delimiters (in my case, a space) as one in the header?
thank you for the above script, it really helped alot as i was struggling, but now i need to add in a filter in the script for a specific field and delete all other irrelevant columns…. any ideas? i need to trip 200 columns down to 25..
I’ve tried a lot of commands but without success. That’s was the only one that worked to me on Powershell.
Thanks a lot.
Could this be edited to take in the data from a SQL Query directly? Where the data from the query was returned to a variable, $ReportTable?
Hi,
I use the script and it works fine except it destroys the German letters: “ä”, “ö”, “ü”, “ß”.
In the csv-files, they are visible. When I manually open the csv-files to excel, it also works.
The word “Ausführungsdatum” from csv looks like “Ausführungsdatum” in Excel.
I could not find the place to put -Encode utf8.
Is there anyone who can assist?
Thanks in advance,
Tim
I just want to do text to columns function in my xlsx.I dont want to convert csv to xlsx.How can i do that ? Can you help me ?
Fantastic thank you! It’s very fast. I had issues getting the comma delimiter to work, but found that by changing the following it worked nicely (Excel 2016 version (Office Pro Plus))
From:
$delimiter=”,”
$query.TextFileOtherDelimiter = $delimiter
To:
$query.TextFileCommaDelimiter = $true
Hello, I am very new to powershell scripting..Above mentioned code works for copying csv to xls file. But entire data in csv which is in comma separated format gets saved in xls single column. How can I split the column into multiple columns pls?
i want to extract specific rows ( say 5 row in the middle) from the csv to xlsx, how can i do it? everything works well but can’t get the required rows only
Hello,
work great for me. But… :)
I thought It will hepl me to workaround issue that excel can show only one bilion entries. Because of that I couldn’t convers my csv file (4 bilions). Script worked, but in xlsx file is only onie bilion entries. Is there any way to break down this limitation ?
Thank you in advance, and great job!
Daniel.
Can you please edit the script to concert ALL csvs in a folder to ONE single xlsx where each csv is one worksheet ?
If the same thing I want for single or 2 columns then what should be the changes.
Can you please edit the script to make a coffe after csv-> xlsx convert?
lmao Some people have no concept of ridicule.
great script!
Fantastic! Saved my bacon! thank you!
Does this require Excel to be installed, I wish to run on a server as a scheduled task?
Great work everyone! The original script works like a charm and the batch script/overwrite function/delete function work great as well.
Appreciate everyones input here! you are all super stars :)
Works great. Just what I needed. I appreciate you.
Excellent article. This helped me understaand how to convert csv to xlsx. I’ve parsed csv’s before but the converting was giving me fits. No more fits. Thank-You! :-)
It is almost exactly what I need, the only hiccup is it does not take into account text qualifiers from the csv. I have files that have part numbers, some of which have leading 0s. e.g. “00073” is converted to 73. Changing the format to text (Change TextFileColumnDataTypes from 1 to 2) as posted by Jan does mean that the leading 0s are treated correctly, but does mean all other numeric fields values are treated as text. Is there a way to use text qualifiers, or to specify that only first column is treated as text?
You’re an absolute legend, this has really saved me from the issue i was plagued with.
i was exporting a csv from using powershell sqlcmd module. as soon as i opened the file in excel, leading zeroes were being trimmed off cells.
your fix allows me to set the columns that contain these cells to a TextFileColumnDataType of 2, which maintains leading zeroes.
all of this massively helps with my automation effort
Can someone share me how to export XLS to CSV with specific data collection from certain rows
I’d use the import excel module, it has a lot of functionalities that are really polished and well thought https://www.powershellgallery.com/packages/ImportExcel/7.1.0
Excellent post.Thank you. My issue is that when I set the script as a task with the task scheduler on a Widows server 2019, it won’t work. I inserted a message msg … in the script so I could actually check the task is running in the test period, I see the message so I get visual confirmation the task is running the script, but there is no conversion. Of course, the script works fine from PowerShell. What could the issue be ?
Hey Adam, first of all thanks for the great content, your site as insta favorite on my browser as soon as I got here. Do you happen to have problems with this code you posted while having another instance of excel open on your desktop? Sometimes when the excel application is oppened this code simply will not work without giving any error messages
You are awesome!!! Beautiful work! Thank you for sharing this script!
Hi Adam, first of all thanks for the useful content. I am new to Perl scripting.
I have a .csv file and need to convert into .xlsx. I am referring you script.
But getting below error. It would be really helpful If you helped me too resolve the errors.
I have placed the file “Test_perl.pl” at below location in Unix server but getting below error.
Using below script
continue to previous comment
I tried to debug the errors and able to resolve few error but still getting below error.
I am using , delimiter in the csv file
Error:
/eis/EIS_INFA_PCS_UATC/SrcFiles/IFRS17/ManData/Intact) $ perl Test_perl.pl
Can’t modify concatenation (.) or string in scalar assignment at Test_perl.pl line 34, near “$delimiter;”
Execution of Test_perl.pl aborted due to compilation errors.
rpwqs494@stha7n0gx(/eis/EIS_INFA_PCS_UATC/SrcFiles/IFRS17/ManData/Intact) $
Using below script
Hi, thx for the great article. Is there a way to also change the decimal seperator and Thousands separator?
tragic not working with greek language characters and i see no columns