从Excel到Image

问题描述 投票:0回答:3

问题:使用python(最好是openpyxl),我可以使用什么或需要做什么将图表导出为图像?

我正在与

openpyxl一起工作,我也有同样的问题。 我在文档中搜索了,但我什么都没得到。经过长时间的浏览后,我在YouTube中找到了解决方案。唯一的问题是我们必须添加另一个库调用“ win32com”

以获取图表,然后将它们保存为图像。
python excel charts openpyxl xlsx
3个回答
3
投票
---解决方案---

import openpyxl from openpyxl.chart import BarChart, Reference from win32com.client import Dispatch #I used Pathlib to get the absolute path of the workspace. import pathlib workbook_file_name = str(pathlib.Path().resolve()) + r"\barChart.xlsx" #With this function I created an example xlsx. def create_xlsx(): wb = openpyxl.Workbook() sheet = wb.active for i in range(10): sheet.append([i]) values = Reference(sheet, min_col=1, min_row=1, max_col=1, max_row=10) chart = BarChart() chart.add_data(values) chart.title = " BAR-CHART " chart.x_axis.title = " X_AXIS " chart.y_axis.title = " Y_AXIS " sheet.add_chart(chart, "E2") wb.save(workbook_file_name) #--- HERE IS THE SOLUTION! --- def export_image(): app = Dispatch("Excel.Application") # It's important to use the absolute path, it won't work with a relative one. workbook = app.Workbooks.Open(Filename=workbook_file_name) app.DisplayAlerts = False for i, sheet in enumerate(workbook.Worksheets): for chartObject in sheet.ChartObjects(): print(sheet.Name + ':' + chartObject.Name) # It's important to use the absolute path, it won't work with a relative one. chartObject.Chart.Export(str(pathlib.Path().resolve()) + "\chart" + str(i+1) + ".png") workbook.Close(SaveChanges=False, Filename=workbook_file_name) def main(): create_xlsx() export_image() if __name__ == "__main__": main()

---模块版本---

openpyxl ==3.0.10

Pywin32==304

---参考---

在这里是视频的链接

I在此读取一些文档上找到了这一点。

如果您知道图像在哪里可以做

from openpyxl_image_loader import SheetImageLoader # Load your workbook and sheet as you want, for example wb = load_workbook('path_to_file.xlsx') sheet = wb['required_sheet'] # Put your sheet in the loader image_loader = SheetImageLoader(sheet) # And get image from specified cell image = image_loader.get('A3') # Image now is a Pillow image, so you can do the following image.show() # Ask if there's an image in a cell if image_loader.image_in('A4): print("Got it!") 如果您不确定工作簿中的图像在哪里,则可以尝试通过单元格进行迭代,直到找到图像为止。


0
投票
导出函数在

'xlwings_chart_object'上不起作用,但确实具有对wincom_object

的引用。

wincom_object
是元组中的第一个项目。然后您可以打电话
api

这对我有用:

0
投票
Export

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.