【问题标题】:xlsxwriter: how to center image in cellxlsxwriter:如何在单元格中居中图像
【发布时间】:2018-07-21 18:13:37
【问题描述】:

我分别使用 set_column 和 set_row 设置列和行的大小,如下所示:

my_worksheet.set_column('A:KK', 17)
my_worksheet.set_row(0, 99.6)

我有这段代码可以将任意大小的图像打印到单元格:

width, height = im.size
# Calculate scale: Problematic
x_scale = IMAGE_CELL_SIZE_PX[0]/float(width) 
y_scale = (IMAGE_CELL_SIZE_PX[1] - 5.0)/float(height)
# Calculate offset: Problematic
x_offset = ((IMAGE_CELL_SIZE_PX[0] - width) / 2.0) / x_scale
y_offset = ((IMAGE_CELL_SIZE_PX[1] - 5 - height) / 2.0) / y_scale
worksheet.insert_image(row, col, image_path, {'x_offset': x_offset, 'y_offset': y_offset, 'x_scale': x_scale, 'y_scale': y_scale})

问题是它不起作用。图像尺寸错误,图片大部分时间远离中心。这就像我错过了一个术语。 主要问题是我无法找到一种方法以独立于机器的方式将像素从像素转换为 Excel 和 xlsxwriter 长度单位。

我只能通过采用 excel 单位的 set_column 设置单元格的宽度,并且我知道以像素为单位的图像尺寸(来自 Pillow Image.size)。显然,两者之间的转换取决于机器。有什么想法吗?

【问题讨论】:

    标签: python xlsxwriter


    【解决方案1】:

    您可以使用 worksheet._size_col()worksheet._size_row() (see here in the code) 将列或行从零开始的索引转换为像素大小。

    要注意的另一件事是 Excel 根据 96 的 DPI 缩放图像。如果图像具有另一个 DPI,则应考虑缩放。这是 XlsxWriter 中 internally 发生的情况,以说明 Excel 的缩放:

        # Scale by non 96dpi resolutions.
        width *= 96.0 / x_dpi
        height *= 96.0 / y_dpi
    

    【讨论】:

      猜你喜欢
      • 2017-06-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-23
      • 1970-01-01
      • 2015-02-20
      • 2013-06-14
      相关资源
      最近更新 更多