我如何使用 xlsxwriter 和 python 将图像添加到 xlsx 文件的 header?

How can i add an image to a header of a xlsx file using xlsxwriter and python?

我想向 xlsx 的 header 添加图像,但它在生成的文件中没有显示任何内容(我们的应用程序选择了一个 .csv,然后使用带有 xlsxwriter 的 .py 文件转换为 .xlsx,并且然后使用 libreoffice 命令转换为 .pdf)

我们已经尝试过不同的图片格式和尺寸,但没有任何区别。

还尝试了库中的示例 (https://xlsxwriter.readthedocs.io/example_headers_footers.html?highlight=set_header),但没有成功。

我们使用了worksheet.insert_image(),它添加了图像但不在header中。这是我们当前的结果:https://ibb.co/QNXv8bM

我们想直接在 header 上添加图像(可能使用 set_header() ),但到目前为止,我们尝试使用此方法还没有产生任何结果。当我们使用 set_header() 放置图像时,它在 header.

上什么也没有显示

这是我们正在使用的 python 文件的一部分:

def create_worksheet(workbook, data, image, p_header_text):
    '''
    Creates and formats worksheet
    :param workbook: Main workbook
    :type workbook: xlsxwriter.Workbook
    :param data: dict with data to use in the worksheet
    :type data: dict
    data example:
    data = {'headings': [head1, head2, ..., headn], 'rows': [[data1, ..., datan], ...]}
    :return: Nothing
    '''
    worksheet = workbook.add_worksheet()
    ### Page Setup
    worksheet.set_margins(top=1.4)
    worksheet.set_landscape()
    worksheet.hide_gridlines(2)
    #worksheet.set_paper(9)  # 9 = A4
    worksheet.fit_to_pages(1, 0)
    ### Header and footer
    header_text = p_header_text
    #worksheet.set_header('&C&16&"Calibri,Bold"{}'.format(header_text))
    worksheet.set_header('&L&G', {'image_left': '/home/reports/LTA-logo.jpg'})


    worksheet.set_footer('&L&D&RPage &P of &N')
    #worksheet.insert_image('A1', '/home/reports/LTA-logo.jpg', {'x_offset': 0, 'y_offset': 0})
    #worksheet.set_header('&C&G', {'image_left': '/home/reports/LTA-logo.jpg'})

    ### Create table
    create_table(worksheet, data)

注意worksheet.set_header('&C&16&"Calibri,Bold"{}'.format(header_text)) 工作正常,它显示 header 上的文本。问题是当我们尝试将图像...

预期的结果是使图像出现在 header 中,与标题左对齐,如图所示:https://ibb.co/vQTytK2

注2:出于商业原因(公司)我无法在打印屏幕上显示数据

它应该与 XlsxWriter 一起使用。您只需要使用 &L 左侧部分和 &C 中间部分以正确的方式构建格式字符串。

例如:

import xlsxwriter

workbook = xlsxwriter.Workbook('headers_footers.xlsx')
worksheet = workbook.add_worksheet('Image')

# Adjust the page top margin to allow space for the header image.
worksheet.set_margins(top=1.3)

worksheet.set_header('&L&[Picture]&C&16&"Calibri,Bold"Revenue Report',
                     {'image_left': 'python-200x80.png'})

workbook.close()

请注意,我在示例中使用了更明确的 &[Picture],但 &G 也适用。

输出: