Python - Converting XLSX to PDF

假装没事ソ 提交于 2019-11-30 23:08:06

Edit: Thanks for the down vote but this is a far more efficient method than trying to load a redundant script that is hard to find and was wrttien in Python 2.7.

  1. Load excel spread sheet into a DataFrame
  2. Write the DataFrame to a HTML file
  3. Convert the html file to an image.

    dirname, fname = os.path.split(source)
    basename = os.path.basename(fname)

    data = pd.read_excel(source).head(6)

    css = """

    """

    text_file = open(f"{basename}.html", "w")
    # write the CSS
    text_file.write(css)
    # write the HTML-ized Pandas DataFrame
    text_file.write(data.to_html())
    text_file.close()

    imgkitoptions = {"format": "jpg"}

    imgkit.from_file(f"{basename}.html", f'{basename}.png', options=imgkitoptions)

    try:
        os.remove(f'{basename}.html')
    except Exception as e:
        print(e)

    return send_from_directory('./', f'{basename}.png')

Taken from here https://medium.com/@andy.lane/convert-pandas-dataframes-to-images-using-imgkit-5da7e5108d55

Works really well, I have XLSX files converting on the fly and displaying as image thumbnails on my application.

from openpyxl import load_workbook
from PDFWriter import PDFWriter

workbook = load_workbook('fruits2.xlsx', guess_types=True, data_only=True)
worksheet = workbook.active

pw = PDFWriter('fruits2.pdf')
pw.setFont('Courier', 12)
pw.setHeader('XLSXtoPDF.py - convert XLSX data to PDF')
pw.setFooter('Generated using openpyxl and xtopdf')

ws_range = worksheet.iter_rows('A1:H13')
for row in ws_range:
    s = ''
    for cell in row:
        if cell.value is None:
            s += ' ' * 11
        else:
            s += str(cell.value).rjust(10) + ' '
    pw.writeLine(s)
pw.savePage()
pw.close()

I have been using this and it works fine

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!