Python - Converting XLSX to PDF

后端 未结 3 1094
长发绾君心
长发绾君心 2020-12-06 13:14

I have always used win32com module in my development server to easily convert from xlsx to pdf:

o = win32com.client.Di         


        
3条回答
  •  暖寄归人
    2020-12-06 14:00

    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.

提交回复
热议问题