excel – Python convert csv to xlsx

excel – Python convert csv to xlsx

Heres an example using xlsxwriter:

import os
import glob
import csv
from xlsxwriter.workbook import Workbook

for csvfile in glob.glob(os.path.join(., *.csv)):
    workbook = Workbook(csvfile[:-4] + .xlsx)
    worksheet = workbook.add_worksheet()
    with open(csvfile, rt, encoding=utf8) as f:
        reader = csv.reader(f)
        for r, row in enumerate(reader):
            for c, col in enumerate(row):
                worksheet.write(r, c, col)

FYI, there is also a package called openpyxl, that can read/write Excel 2007 xlsx/xlsm files.

Hope that helps.

With my library pyexcel,

 $ pip install pyexcel pyexcel-xlsx

you can do it in one command line:

from pyexcel.cookbook import merge_all_to_a_book
# import pyexcel.ext.xlsx # no longer required if you use pyexcel >= 0.2.2 
import glob

merge_all_to_a_book(glob.glob(your_csv_directory/*.csv), output.xlsx)

Each csv will have its own sheet and the name will be their file name.

excel – Python convert csv to xlsx

First install openpyxl:

pip install openpyxl


from openpyxl import Workbook
import csv

wb = Workbook()
ws = wb.active
with open(test.csv, r) as f:
    for row in csv.reader(f):

Leave a Reply

Your email address will not be published. Required fields are marked *