Saturday, 26 August 2017

microsoft excel - How to batch convert .csv to .xls/xlsx


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?



Answer



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

No comments:

Post a Comment

Where does Skype save my contact's avatars in Linux?

I'm using Skype on Linux. Where can I find images cached by skype of my contact's avatars? Answer I wanted to get those Skype avat...