简体   繁体   中英

how to insert my data into an existing excel file

Hello guys I created an excel and I change the width and the height of some cells and I would like to insert a dataframe into this modified excel however I don't know how to do it, did someone have any idea? my code below:

from openpyxl import Workbook

wb = Workbook()
ws = wb.active

ws.column_dimensions['A'].width = 10

ws.column_dimensions['B'].width = 10

ws.column_dimensions['C'].width = 50

ws.column_dimensions['D'].width = 130 

ws.column_dimensions['E'].width = 30

ws.column_dimensions['F'].width = 10

ws.row_dimensions[1].height = 150

ws.row_dimensions[2].height = 150

ws.row_dimensions[3].height = 150

ws.row_dimensions[4].height = 150 

ws.row_dimensions[5].height = 150

ws.row_dimensions[6].height = 150

wb.save(filename='t.xlsx')


data = {'first': [1], 'second': [2], 'third': [3], 'fourth': [4]}

t = pd.DataFrame(data,columns = ['first', 'second', 'third','fourth'])

First

import pandas and import full openpyxl module

import pandas as pd
import openpyxl as xl

Second

the method for inputting a pandas dataframe into an Excel Sheet is:

df.to_excel([file path])

Note: you can also specify the Excel sheet by adding the sheet name

df.to_excel([file_path], sheet=[name of sheet])

So, you need to add this line of code to input your df "t"

t.to_excel('t.xlsx')

Third

Rearrange your code sequence so that you create and input your dataframe into Excel first. If you format the Excel sheet and then use this pandas method, it will reset all of your formatting (there are workarounds to this - but they take longer).

Last Step

Since pandas will create the excel workbook when you input your dataframe, you need to change:

wb = Workbook() to wb = xl.load_workbook('t.xlsx')

Result

Here's the updated code and a snapshot of the results after running it

import pandas as pd
import openpyxl as xl

data = {'first': [1], 'second': [2], 'third': [3], 'fourth': [4]}

t = pd.DataFrame(data,columns = ['first', 'second', 'third','fourth'])
t.to_excel('t.xlsx')

wb = xl.load_workbook('t.xlsx')
ws = wb.active

ws.column_dimensions['A'].width = 10

ws.column_dimensions['B'].width = 10

ws.column_dimensions['C'].width = 50

ws.column_dimensions['D'].width = 130 

ws.column_dimensions['E'].width = 30

ws.column_dimensions['F'].width = 10

ws.row_dimensions[1].height = 150

ws.row_dimensions[2].height = 150

ws.row_dimensions[3].height = 150

ws.row_dimensions[4].height = 150 

ws.row_dimensions[5].height = 150

ws.row_dimensions[6].height = 150

wb.save(filename='t.xlsx')

Snapshot of result in Excel 't.xlsx'

在此处输入图像描述

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