14

I am looking for a way to quickly convert a directory of .csv files into the .xls or .xlsx format (would be nice if I could do either/or).

Is there an easy way to do this or do I need to install a third party program?

3
  • 1
    Not sure why you would need to do so. csv's open well in excel. anyone needing to interact could just open without issue.
    – Jody
    Jun 24, 2011 at 0:28
  • 2
    You are right Excel opens csv and xls/xlsx just fine. Other programs, however, do not. =) Jun 24, 2011 at 0:37
  • 1
    So what program are you looking to use this in?
    – Kirk
    Jun 24, 2011 at 2:21

7 Answers 7

22

Assuming you like and have Python (for some reason), you could use this script I whipped up:

import os
import glob
import csv
import xlwt # from http://www.python-excel.org/

for csvfile in glob.glob(os.path.join('.', '*.csv')):
    wb = xlwt.Workbook()
    ws = wb.add_sheet('data')
    with open(csvfile, 'rb') as f:
        reader = csv.reader(f)
        for r, row in enumerate(reader):
            for c, val in enumerate(row):
                ws.write(r, c, val)
    wb.save(csvfile + '.xls')

Ran in the directory with all the CSV files, it will convert them all and slap a ".xls" onto the end.

For Excel 2007+ (xlsx files) supporting up to about 1 Mrows:

import os
import glob
import csv
import openpyxl # from https://pythonhosted.org/openpyxl/ or PyPI (e.g. via pip)

for csvfile in glob.glob(os.path.join('.', '*.csv')):
    wb = openpyxl.Workbook()
    ws = wb.active
    with open(csvfile, 'rb') as f:
        reader = csv.reader(f)
        for r, row in enumerate(reader, start=1):
            for c, val in enumerate(row, start=1):
                ws.cell(row=r, column=c).value = val
    wb.save(csvfile + '.xlsx')
1
  • 2
    On a Macintosh, I used the xlsx version above. I had to change "rb" to "rU" to get around the "universal-newline mode" error from Python. Using "start=1" for "rows in enumerate" and "val in enumerate" created a blank row above and a blank column left of the actual data. I changed both to "start=0", which started the data in cell A1 (upper left) of the spreadsheet (Excel 2011). I also changed the last line to "wb.save(os.path.splitext(csvfile)[0] + '.xlsx')" to remove the .csv part of the file (e.g., nnnn.csv.xlsx to nnnn.xlsx). Oct 13, 2015 at 0:34
2

I sympathise with you! I had to do this same conversion. I was trying to manipulate data using openpyxl but for some reason it wasn't doing what I wanted with with csv files so had to convert to xlsx first.

I used Python and Pandas. I am using Python 3.

import pandas as pd
import os

for (dirname, dirs, files) in os.walk('.'): #source directory
for filename in files:
        if filename.endswith('.csv'):
            df = pd.read_csv(filename)
            df.to_excel(filename + '.xlsx')
            os.remove(filename)  #deletes csv file
1
  • 1
    I would suggest to add a note that the last line deletes the csv file – could be dangerous otherwise if just copy-pasting the code since this is not a feature asked for as far as I see. Jul 14, 2020 at 12:33
1

Here is a perl script that supposedly does it, but it does seem like a lot of work to do something that is already built into Excel.

0
1

There is a lot left unsaid in your question.

Assuming that your CVS files are in a directory structure similar to

c:\randompath\CSV\
    a.csv
    b.csv
    c.csv
      :
      :
    z.csv

and you want to end up with

c:\randompath\XLS\
    a.xls
    b.xls
    c.xls
      :
      :
    z.xls

I can think of three routes to go depending on the ratio of upfront work to clean-up work you are willing to do.

  1. No Precoding: Use Windows Explorer to navigate to the CSV files use whatever method works best to select the files to be converted (lasso, ctrl+a, ctrl+click, shift+click) then right click one of the selected files and click on Open. This will open all the files in Excel. Then for each file you can select "File" and "Save as" and finally choose the new file format you want it saved to.
  2. A Simple Batch File: That batch file could use wild cards and/or a for each loop structure to open each of the CSV files for you and then you could manually process them as before.
  3. Create a VBA program within an Excel Spreadsheet: VBA could automatically opens each CSV file and then saves it to an Excel format. You could even add a simple message box that offers a choice of either xls or xlsx as each file is opened.

Note that I haven't written any code to do these things (yet) I am just offering ideas for a starting point. Perhaps if you could give more details about what you want you could get more detailed explanations for how to handle approach from me or another forum member.

1

For Windows? CoolUtils "Total CSV Converter" command line version supports many output formats including JSON, Access, DBF, XML & SQL and is only $40. It can recurse sub-directories, delete original CSV files, combine all files to one document, and more.

http://www.coolutils.com/TotalCSVConverter

CSVConverter.exe <source> <destination> <options>

"Advanced CSV Converter" ($40-200) is a portable EXE that can do it quickly and without Excel having to be installed.

http://www.dbf2002.com/csv-converter/commandline.html

"c:\Program Files\CSV Converter\csvcnv.exe" c:\base\*.csv c:\exports\ /TOXLSX /SRCHDR

SoftInterface's "Convert XLS" can use Excel (but is not required) and is more expensive ($500+), but supports more formats and has more options.

http://www.softinterface.com/Convert-XLS/Convert-XLS.htm

"c:\Program Files (x86)\Softinterface, Inc\Convert XLS\ConvertXLS.exe" /V /S"c:\base\*.csv" /T"c:\exports\*.xlsx" /F6 /C51 /M2

"Gnumeric" is an open-source spreadsheet program that can perform a direct conversion, but it was discontinued for Windows in Aug 2014.

http://www.gnumeric.org/

ssconvert file.csv file.xlsx

If you have Python installed, "csv2odf" is a open-source option and uses a templated approach to generate ods, odt, html, xlsx, or docx files.

http://sourceforge.net/projects/csv2odf/

csv2odf data.csv template.odt output.xlsx
1
  • Here in 2024. csv2odf worked for me for python 3.9 and 3.11, without any extra modules, with only a couple changes. Change #! line to python3. Add import html. Use html.escape instead of cgi.escape.
    – jrw32982
    Feb 23 at 17:01
0

With Node 8+ and bash:

npm install -g pguardiario/csv2xlsx

for file in *.csv; do csv2xlsx "$file"; done
-1

The Easy way: open your csv file from Microsoft Excel, convert text to columns (select the cells/text, click Menu - Data - Text to Columns) set your option to convert.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .