stu6000
stu6000

Reputation: 33

Copy .csv files into a .xlsx workbook using python

I have done extensive researches, however have not been able to come up with the right solution for my needs.

I have python script which generates multiple .csv files.

Each .csv file only has data in column A & B.

Each .csv file has a unique name, and im trying to work out how to copy the .csv file based on its name, into an existing excel workbook, into a specific tab/sheet of the same name.

The .csv files will always be in the same folder.

I would ideally like to use python for this task.

Upvotes: 3

Views: 9844

Answers (2)

Rajarshi Das
Rajarshi Das

Reputation: 12320

You can try something like this

import os
import glob
import csv
from xlsxwriter.workbook import Workbook
workbook = Workbook('Existing.xlsx')

for csvfile in glob.glob(os.path.join('.', '*.csv')):
    worksheet = workbook.add_worksheet(os.path.splitext(csvfile)[0]) # worksheet with csv file name
    with open(csvfile, 'rb') as f:
        reader = csv.reader(f)
        for r, row in enumerate(reader):
            for c, col in enumerate(row):
                worksheet.write(r, c, col) # write the csv file content into it
 workbook.close()

Upvotes: 5

JianMing Wang
JianMing Wang

Reputation: 1169

using module csv to read data from csv file and write .xlsx(https://pypi.python.org/pypi/XlsxWriter) with XlsxWriter is recommended

Upvotes: 1

Related Questions