简体   繁体   中英

How to import a csv file content into excel via python

I would need to import the content of a csv file into an excel worksheet which is already created and shall not change (while the content of the csv can be overwritten).

For now I am using Excelwriter to create an excel file with the csv reader

from pandas.io.excel import ExcelWriter

import pandas
csv_file = 'name.csv'


 ew = ExcelWriter('name.xlsx',sheet_name='name')
 pandas.read_csv(csv_file, decimal=',').to_excel(ew, sheet_name=csv_file)
 ew.save()

Then I could copy the "ew" excel content into another excel file, but:

Is there any way to read a csv file inot a specific workbook tab directly? basically to import a csv file into excel in a specific tab.

Thank you!

This is edited a bit from import csv to xlsx python

# First, import the .csv file
import pandas as pandas
df = pd.read_csv(my_filename)

# Now, open the book you are going to overwrrite
book = load_workbook(name.xlsx)
sheet_name = 'name'
# You specified both as name

# Assuming you are overwriting the same book...
with pd.ExcelWriter(name.xlsx, engine='openpyxl')  as writer:

    writer.book = book
    writer.sheets = dict((ws.title, ws) for ws in book.worksheets)

    df.to_excel(writer, sheet_name=sheet_name, startrow=1, startcol=10, engine='openpyxl')

The code is commented within.

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