如何使用 win32com 将 Excel Range 保存为矢量图形文件

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

TL;博士

这是不正确的:

# Vector Graphics
ws.Range(ws.Cells(1,1),ws.Cells(7,5)).CopyPicture(Format = 1).Export('test.wmf')

使用

.wmf
将该图片导出到
win32com
文件的正确方法是什么?

完整版

我一直在尝试使用 Python 将 xlsx 文件中的一系列单元格保存为漂亮的图像。

我更喜欢PNG而不是JPEG,因为两者之间的水平和垂直规则的外观有何不同。

我最喜欢的是 SVG,但我没能找到它作为一个选项。

现在,我一直在使用这种方法(改编自herehere):

import win32com.client
from PIL import ImageGrab, Image

o = win32com.client.Dispatch('Excel.Application')
o.visible = False

wb = o.Workbooks.Open(path + fname)
ws = wb.Worksheets['Sheet1']

# copy and save as image
ws.Range(ws.Cells(1,1),ws.Cells(7,5)).CopyPicture(Format = 2)
img = ImageGrab.grabclipboard()

# to increase resolution
factor = 4 
length_x, width_y = img.size
size = int(factor * length_x), int(factor * width_y)
img_resize = img.resize(size, Image.Resampling.LANCZOS)

# save as png
imgFile = os.path.join(img_path,'test.png')
img.save(imgFile, 'PNG', compress_level=0, dpi=(500, 500))

但是,它看起来不太好,增加

factor
DPI似乎并没有让它看起来很好。

我读过

PIL
可以读取EMFWMF文件,所以我想我可以将
CopyPicture(Format = 1)
保存到文件中,以非常高的DPI在PIL中读取它,然后将其另存为PNG.

# Vector Graphics
ws.Range(ws.Cells(1,1),ws.Cells(7,5)).CopyPicture(Format = 1).Export('test.wmf')

with Image.open("test.wmf") as im:
    im.load(dpi=500)

但是,我的代码抛出错误:

AttributeError: 'bool' object has no attribute 'Export'

...毫无疑问,由于我不知道如何将 win32com 用于 MS Excel。

excel python-imaging-library win32com
© www.soinside.com 2019 - 2024. All rights reserved.