[英]Python: Write a dataframe to an already existing excel which contains a sheet with images
I have been working on this for too long now. 我已经为此工作了太久了。 I have an Excel with one sheet (sheetname = 'abc') with images in it and I want to have a Python script that writes a dataframe on a second separate sheet (sheetname = 'def') in the same excel file. 我有一个带有一张带有图像的工作表(sheetname ='abc')的Excel,我想拥有一个Python脚本,该脚本在同一excel文件的第二张单独的工作表(sheetname ='def')上写一个数据框。 Can anybody provide me with some example code, because everytime I try to write the dataframe, the first sheet with the images gets emptied. 谁能提供一些示例代码,因为每次我尝试编写数据帧时,带有图像的第一张纸都会被清空。
This is what I tried: 这是我尝试的:
book = load_workbook('filename_of_file_with_pictures_in_it.xlsx')
writer = pd.ExcelWriter('filename_of_file_with_pictures_in_it.xlsx', engine = 'openpyxl')
writer.book = book
x1 = np.random.randn(100, 2)
df = pd.DataFrame(x1)
df.to_excel(writer, sheet_name = 'def')
writer.save()
book.close()
It saves the random numbers in the sheet with the name 'def', but the first sheet 'abc' now becomes empty. 它将随机数保存在名称为“ def”的工作表中,但是第一张工作表“ abc”现在变为空。
What goes wrong here? 这里出什么问题了? Hopefully somebody can help me with this. 希望有人可以帮助我。
Interesting question! 有趣的问题! With openpyxl you can easily add values, keep the formulas but cannot retain the graphs. 使用openpyxl,您可以轻松添加值,保留公式但不能保留图形。 Also with the latest version (2.5.4), graphs do not stay. 在最新版本(2.5.4)中,图形也不会保留。 So, I decided to address the issue with xlwings : 因此,我决定使用xlwings解决此问题:
import xlwings as xw
wb = xw.Book(r"filename_of_file_with_pictures_in_it.xlsx")
sht=wb.sheets.add('SheetMod')
sht.range('A1').value = np.random.randn(100, 2)
wb.save(r"path_new_file.xlsx")
With this snippet I managed to insert the random set of values and saved a new copy of the modified xlsx.As you insert the command, the excel file will automatically open showing you the new sheet- without changing the existing ones (graphs and formulas included). 借助此代码段,我设法插入了随机值集并保存了修改后的xlsx的新副本。当您插入命令时,excel文件将自动打开,向您显示新工作表-无需更改现有工作表(包括图形和公式) )。 Make sure you install all the interdependencies to get xlwings to run in your system. 确保安装所有相互依赖性,以使xlwings在系统中运行。 Hope this helps! 希望这可以帮助!
为此,您需要使用像Openpyxl之类的Excel'reader'或类似的工具与Pandas结合使用,pandas的to_excel函数仅是写操作,因此在打开文件时不会在意文件中的内容。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.