在macOS下使用XlsxWriter的.insert_image()控制图片尺寸与形状
解决macOS版Excel中XlsxWriter插入图片缩放参数失效问题
问题分析
核心矛盾是macOS与Windows版Excel的DPI渲染逻辑差异:XlsxWriter的insert_image()默认基于Windows的96DPI计算缩放比例,但macOS版Excel使用72DPI渲染,导致x_scale/y_scale参数被忽略,图片尺寸被单元格维度强制适配。你的环境为Excel for Mac 16.66.1、XlsxWriter 1.3.7,测试图片为200x200像素/72DPI。
解决方案
方案1:直接指定图片尺寸+匹配单元格维度
放弃依赖缩放参数,直接设置图片像素尺寸,同时调整对应单元格的列宽和行高,确保图片完全适配且不被拉伸:
修改后的代码:
import xlsxwriter def create_workbook(filename=None): if not isinstance(filename, str) or len(filename) == 0: filename = 'testwriter.xlsx' if isinstance(filename, str) and filename[-5:] != '.xlsx': filename += '.xlsx' workbook = xlsxwriter.Workbook(filename) workbook.window_width = 25000 workbook.window_height = 16000 fs = 14 # font size formats = dict() formats['header'] = workbook.add_format({'font_size': fs, 'align': 'center'}) formats['info'] = workbook.add_format({'font_size': fs, 'align': 'left', 'font': 'Courier'}) return workbook, formats def create_sheet(workbook, sheetname, formats, n_columns, img_size): sheetname_local = str(sheetname) if not isinstance(sheetname_local, str) or len(sheetname_local) == 0: sheetname_local = 'noname' sheet = workbook.add_worksheet(sheetname_local) # 默认字体1字符≈7.5像素,计算适配图片宽度的列宽 img_col_width = img_size[0] / 7.5 widths = [20] + n_columns*[img_col_width] headings = ['name'] + ['imgs ' + str(i+1) for i in range(n_columns)] for i, (w, h) in enumerate(zip(widths, headings)): sheet.set_column(i, i, w) sheet.write(0, i, h, formats['header']) return sheet workbook, formats = create_workbook(filename='testAB.xlsx') # 定义目标图片尺寸 img_size = (200, 200) sheet = create_sheet(workbook, '2021', formats, n_columns=3, img_size=img_size) img_fname = 'ima.jpg' # 插入A2单元格:设置对应行高(72DPI下1像素=1磅) sheet.set_row(1, img_size[1]) sheet.insert_image('A2', img_fname, { 'width': img_size[0], 'height': img_size[1], 'object_position': 2 # 图片仅随单元格移动,不自动调整大小 }) # 插入B13单元格:调整对应行高 sheet.set_row(12, img_size[1]) sheet.insert_image('B13', img_fname, { 'width': img_size[0], 'height': img_size[1], 'object_position': 2 }) workbook.close()
方案2:适配DPI调整缩放比例
若坚持使用缩放参数,需将XlsxWriter的96DPI缩放比例转换为macOS Excel的72DPI适配值:
- 实际缩放比例 = 期望比例 × (72/96) = 期望比例 × 0.75
例如要实现1:1显示,代码调整为:
sheet.insert_image('A2', img_fname, { 'x_scale': 0.75, 'y_scale': 0.75, 'object_position': 2 })
同时仍需调整对应单元格的列宽和行高,避免图片被单元格挤压。
关键注意点
object_position=2表示图片仅随单元格移动但不调整大小,需确保单元格维度足够容纳图片;若设为1,图片会随单元格拉伸,破坏尺寸统一。- 列宽计算基于默认字体(Arial 10号)的字符宽度,若修改字体需重新计算列宽系数。
内容的提问来源于stack exchange,提问作者uhoh
相关产品推荐
相关产品推荐

