将值写入python中 pandas 表中的特定单元格 [英] Write values to a particular cell in a sheet in pandas in python

查看:523
本文介绍了将值写入python中 pandas 表中的特定单元格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Excel工作表,该工作表在某些单元格中已经有一些值.

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

例如:-

        A      B      C      D
1      val1   val2          val3
2             valx   valy        

我希望熊猫在不触摸其他任何单元格,纸张等的情况下写特定的单元格

这是我尝试过的代码.

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 have reffered to :- How to write to an existing excel file without overwriting data (using pandas)? but this solution does not work.

推荐答案

我无法使用熊猫来完成我在问题中提出的要求,但是可以使用Openpyxl解决它.

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

因此,Openpyxl可以在不触及其他工作表,单元格等的情况下写入一个网状单元格. 基本上,它会尊重原始文件的属性写入新文件

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

这篇关于将值写入python中 pandas 表中的特定单元格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆