Traceback (most recent call last): File "D:/WORK/PYWork/demo/test_13.py", line 16, in <module> img_height = (max_row - min_row + 1) * cell_height TypeError: unsupported operand type(s) for *: 'int' and 'NoneType'
时间: 2024-03-15 11:45:34 浏览: 151
linux 下 pip3 报错“ File “/usr/bin/pip3”, line 9, in from pip import mainImportError: canno”处理
5星 · 资源好评率100%
这个错误的原因是openpyxl库中的row_dimensions和column_dimensions属性返回的是NoneType类型,而不是具体的行高或列宽度。这可能是因为你的Excel文件中没有设置行高或列宽度。
为了解决这个问题,你可以手动设置行高和列宽度,或者使用默认值。以下是两种解决方案:
1. 手动设置行高和列宽度:
```python
from openpyxl import load_workbook
from openpyxl.utils import range_boundaries
from PIL import Image, ImageDraw
# 打开Excel文件
workbook = load_workbook(filename='example.xlsx')
# 选择要截图的单元格范围
worksheet = workbook['Sheet1']
min_col, min_row, max_col, max_row = range_boundaries('A1:C10')
# 获取单元格范围的像素大小
cell_width = 100 # 手动设置列宽度
cell_height = 20 # 手动设置行高度
img_width = (max_col - min_col + 1) * cell_width
img_height = (max_row - min_row + 1) * cell_height
# 创建空白图片
img = Image.new('RGB', (img_width, img_height))
# 遍历单元格范围,将单元格内容绘制到图片上
for row in range(min_row, max_row + 1):
for col in range(min_col, max_col + 1):
cell = worksheet.cell(row=row, column=col)
value = cell.value
x = (col - min_col) * cell_width
y = (row - min_row) * cell_height
img.paste((255, 255, 255), (x, y, x + cell_width, y + cell_height))
img_draw = ImageDraw.Draw(img)
img_draw.text((x, y), str(value), fill=(0, 0, 0))
# 保存图片
img.save('sheet1.png')
```
在上面的代码中,我们手动设置了列宽度为100,行高度为20,这样就可以避免row_dimensions和column_dimensions属性返回NoneType类型的问题。
2. 使用默认值:
```python
from openpyxl import load_workbook
from openpyxl.utils import range_boundaries
from openpyxl.utils.units import pixels_to_points
from PIL import Image, ImageDraw
# 打开Excel文件
workbook = load_workbook(filename='example.xlsx')
# 选择要截图的单元格范围
worksheet = workbook['Sheet1']
min_col, min_row, max_col, max_row = range_boundaries('A1:C10')
# 获取单元格范围的像素大小
cell_width = pixels_to_points(worksheet.column_dimensions['A'].width)
cell_height = pixels_to_points(worksheet.row_dimensions[1].height)
img_width = (max_col - min_col + 1) * cell_width
img_height = (max_row - min_row + 1) * cell_height
# 创建空白图片
img = Image.new('RGB', (img_width, img_height))
# 遍历单元格范围,将单元格内容绘制到图片上
for row in range(min_row, max_row + 1):
for col in range(min_col, max_col + 1):
cell = worksheet.cell(row=row, column=col)
value = cell.value
x = (col - min_col) * cell_width
y = (row - min_row) * cell_height
img.paste((255, 255, 255), (x, y, x + cell_width, y + cell_height))
img_draw = ImageDraw.Draw(img)
img_draw.text((x, y), str(value), fill=(0, 0, 0))
# 保存图片
img.save('sheet1.png')
```
在上面的代码中,我们使用了openpyxl库中的pixels_to_points函数将像素大小转换为默认的点大小。这样就可以避免row_dimensions和column_dimensions属性返回NoneType类型的问题。
阅读全文