将值写入python中熊猫表中的特定单元格

发布于 2021-01-29 15:07:50

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

对于前:-

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

但是,此代码将删除较旧的单元格值。

我已经提到过:-如何在不覆盖数据的情况下(使用熊猫)写入现有的excel文件?
但是此解决方案不起作用。

关注者
0
被浏览
88
1 个回答
  • 面试哥
    面试哥 2021-01-29
    为面试而生,有面试问题,就找面试哥。

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

    我将编写一些代码片段,以帮助实现所要求的内容。

    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会在不触摸其他工作表,单元格等的情况下写入一个网状单元。



知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看