python往excel特定单元格中写入文本_将值写入python中熊猫表中的特定单元格

I have an excel sheet, which already has some values in some cells.

For ex :-

A B C D

1 val1 val2 val3

2 valx valy

I want pandas to write to specific cells without touching any other cells,sheet etc

This is the code i tried.

import pandas as pd

from openpyxl import load_workbook

df2 = pd.DataFrame({'Data': [13, 24, 35, 46]})

book = load_workbook('b.xlsx')

writer = pd.ExcelWriter('b.xlsx', engine='openpyxl')

df2.to_excel(writer, "Sheet1", startcol=7,startrow=6)

writer.save()

However this code deletes the older cell values.

解决方案

I was not able to do what was asked by me in the question by using pandas, but was able to solve it by using Openpyxl.

I will write few code snippets which would help in achieving what was asked.

import openpyxl

srcfile = openpyxl.load_workbook('docname.xlsx',read_only=False, keep_vba= True)#to open the excel sheet and if it has macros

sheetname = srcfile.get_sheet_by_name('sheetname')#get sheetname from the file

sheetname['B2']= str('write something') #write something in B2 cell of the supplied sheet

sheetname.cell(row=1,column=1).value = "something" #write to row 1,col 1 explicitly, this type of writing is useful to write something in loops

srcfile.save('newfile.xlsm')#save it as a new file, the original file is untouched and here I am saving it as xlsm(m here denotes macros).

So Openpyxl writes to a purticular cell, without touching the other sheets,cells etc.

It basically writes to a new file respecting the properties of the original file

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值