简体   繁体   中英

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM