上一篇咱們實現了多個表格數據合併到一個表格,本次咱們來學習如何將表格數據分開導出為PDF文件。 部分數據 然後需要安裝一下這個軟體 wkhtmltopdf 效果展示 將每個數據單獨導出為一個PDF 代碼實現 import pdfkit import openpyxl import os # Pyth ...
上一篇咱們實現了多個表格數據合併到一個表格,本次咱們來學習如何將表格數據分開導出為PDF文件。
部分數據

然後需要安裝一下這個軟體 wkhtmltopdf
效果展示

將每個數據單獨導出為一個PDF

代碼實現
import pdfkit import openpyxl import os # Python學習交流群 815624229 target_dir = '經銷商預算' if not os.path.exists(target_dir): os.mkdir(target_dir) html = """ <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <style> table { font-size: 22px; font-weight: bolder; width: 850px; } </style> </head> <body> <table border="1" align="center" cellspacing="1"> <tr> <td class='title' align="center" colspan="6">2020年廣東經銷商預算目標</td> </tr> <tr> <td>經銷商代碼</td> <td>經銷商名稱</td> <td>成車數量</td> <td>成車金額</td> <td>商品金額</td> <td>客戶簽字</td> </tr> <tr> <td>{code}</td> <td>{name}</td> <td>{number}</td> <td>{money}</td> <td>{total}</td> <td></td> </tr> </table> </body> </html> """ def html_to_pdf(filename_html, filename_pdf): """HTML 2 PDF""" config = pdfkit.configuration(wkhtmltopdf='D:\\wkhtmltopdf\\bin\\wkhtmltopdf.exe') pdfkit.from_file(filename_html, filename_pdf, configuration=config) wb = openpyxl.load_workbook('2020經銷商目標.xlsx') sheet = wb['Sheet1'] print(sheet.rows) for row in list(sheet.rows)[3:]: data = [value.value for value in row] data = data[1:-1] format_html = html.replace('{code}', data[0]) format_html = format_html.replace('{name}', data[1]) format_html = format_html.replace('{number}', str(data[2])) format_html = format_html.replace('{money}', f'{data[3]:.2f}') format_html = format_html.replace('{total}', f'{data[4]:.2f}') with open('example.html', mode='w', encoding='utf-8') as f: f.write(format_html) html_to_pdf('example.html', target_dir + os.path.sep + data[0] + " " + data[1] + '.pdf')
喜歡的小伙伴記得點贊收藏呀~
關註我分享更多技術乾貨
直接拿走代碼等於白嫖,點贊收藏才是真情…
你們的支持是我更新的動力!