Python自动化办公:将Excel表格内容批量导出为PDF文件

x33g5p2x  于2022-04-16 转载在 Python  
字(1.9k)|赞(0)|评价(0)|浏览(664)

序言

上一篇咱们实现了多个表格数据合并到一个表格,本次咱们来学习如何将表格数据分开导出为PDF文件。

部分数据

然后需要安装一下这个软件 wkhtmltopdf
不知道怎么下载的可以在电脑端左侧扫一下找到我要

效果展示


将每个数据单独导出为一个PDF

代码实现

  1. import pdfkit
  2. import openpyxl
  3. import os
  4. target_dir = '经销商预算'
  5. if not os.path.exists(target_dir):
  6. os.mkdir(target_dir)
  7. html = """
  8. <!DOCTYPE html>
  9. <html lang="en">
  10. <head>
  11. <meta charset="UTF-8">
  12. <style>
  13. table {
  14. font-size: 22px;
  15. font-weight: bolder;
  16. width: 850px;
  17. }
  18. </style>
  19. </head>
  20. <body>
  21. <table border="1" align="center" cellspacing="1">
  22. <tr>
  23. <td class='title' align="center" colspan="6">2020年广东经销商预算目标</td>
  24. </tr>
  25. <tr>
  26. <td>经销商代码</td>
  27. <td>经销商名称</td>
  28. <td>成车数量</td>
  29. <td>成车金额</td>
  30. <td>商品金额</td>
  31. <td>客户签字</td>
  32. </tr>
  33. <tr>
  34. <td>{code}</td>
  35. <td>{name}</td>
  36. <td>{number}</td>
  37. <td>{money}</td>
  38. <td>{total}</td>
  39. <td></td>
  40. </tr>
  41. </table>
  42. </body>
  43. </html>
  44. """
  45. def html_to_pdf(filename_html, filename_pdf):
  46. """HTML 2 PDF"""
  47. config = pdfkit.configuration(wkhtmltopdf='D:\\wkhtmltopdf\\bin\\wkhtmltopdf.exe')
  48. pdfkit.from_file(filename_html, filename_pdf, configuration=config)
  49. wb = openpyxl.load_workbook('2020经销商目标.xlsx')
  50. sheet = wb['Sheet1']
  51. print(sheet.rows)
  52. for row in list(sheet.rows)[3:]:
  53. data = [value.value for value in row]
  54. data = data[1:-1]
  55. format_html = html.replace('{code}', data[0])
  56. format_html = format_html.replace('{name}', data[1])
  57. format_html = format_html.replace('{number}', str(data[2]))
  58. format_html = format_html.replace('{money}', f'{data[3]:.2f}')
  59. format_html = format_html.replace('{total}', f'{data[4]:.2f}')
  60. with open('example.html', mode='w', encoding='utf-8') as f:
  61. f.write(format_html)
  62. html_to_pdf('example.html', target_dir + os.path.sep + data[0] + " " + data[1] + '.pdf')

喜欢的小伙伴记得点赞收藏呀~
关注我分享更多技术干货
直接拿走代码等于白嫖,点赞收藏才是真情…
你们的支持是我更新的动力!

相关文章