如何使用xlsxwriter和python向xlsx文件的头添加图像?

2024-04-18 07:12:37 发布

您现在位置:Python中文网/ 问答频道 /正文

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

我们已经尝试过不同的图像格式和大小,但没有什么不同。在

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

我们使用了worksheet.insert_image(),它添加了图像,但没有添加到标题中。这是我们目前的结果:https://ibb.co/QNXv8bM

我们希望直接将图像添加到头上(可能使用set_header()),但是到目前为止,我们使用这个方法的尝试还没有产生任何结果。当我们使用set_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))工作正常,它在标题上显示文本。问题是当我们试图把图像。。。在

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

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


Tags: 文件texthttps图像image标题homedata
1条回答
网友
1楼 · 发布于 2024-04-18 07:12:37

它应该与XlsxWriter一起工作。您只需要以正确的方式构建格式字符串,左边是&L,中间部分是{}。在

例如:

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也可以。在

输出:

enter image description here

相关问题 更多 >