Convert Excel file (XLSX) to CSV in Powershell

The are several steps you have to take in order to convert XLSX to CSV in Powershell, but before you do that, create your Excel file and save it.

Saving a file

I’m going to use a list of a few names and ages saved as the XLSX file. What you need to remember is that the file should only have one worksheet, otherwise the function will display information on whether to override the first sheet with the second one.

I saved it in the following location:

Open the Powershell window

After you open the Powershell window, copy this code and insert it with the right mouse click.

It’s going to create a new csv file.

If you open a CSV file in a text editor, for example, notepad++, you are going to have words separated by commas.

Function Explanation

Here, we set the directory and file location.

This code creates a COM object to use Excel features.

Open the Excel file.

The next part is the foreach loop that saves each sheet as a file. If you have multiple sheets inside a worksheet it will as you whether you want to override.

SaveAs uses 6 as a second parameter. You need to add it, so the file will be saved as a text form, and the application will not try to save formatting.

If you try to save formatting, you would get a bunch of rubbish if you open the file inside a text editor.

Convert multiple sheets into multiple files

At the beginning of this lesson, I wrote that you should have only one sheet inside the workbook. We can easily modify the code, to handle a workbook with multiple sheets.

Replace this code:

And paste this code:

Now, run the code, and the function will create a new file for each worksheet.

Tomasz Decker is an Excel specialist, skilled in data analysis and financial modeling.