当前位置:   article > 正文

Excel批量转换PDF,python脚本_python excle转pdf

python excle转pdf

#创作灵感 前一阵有很多粉丝关注到之前的一篇文章,关于用VBS脚本批量将Word转换为PDF文件,有粉丝私信我,有没有excel转换pdf的,网上查了一些VBS脚本,似乎没有能用的,我就用python编写了一个脚本,测试没什么问题。

脚本如下:

  1. import os
  2. from tkinter import Tk, Label, Button, filedialog
  3. from openpyxl import load_workbook
  4. from reportlab.pdfgen import canvas
  5. class ExcelToPdfConverter:
  6. def __init__(self, root):
  7. self.root = root
  8. self.root.title("Excel to PDF Converter")
  9. self.excel_folder_path = ""
  10. self.pdf_folder_path = ""
  11. self.label_excel = Label(root, text="Excel文件夹路径:")
  12. self.label_excel.pack()
  13. self.button_excel = Button(root, text="选择Excel文件夹", command=self.choose_excel_folder)
  14. self.button_excel.pack()
  15. self.label_pdf = Label(root, text="PDF文件夹路径:")
  16. self.label_pdf.pack()
  17. self.button_pdf = Button(root, text="选择PDF文件夹", command=self.choose_pdf_folder)
  18. self.button_pdf.pack()
  19. self.convert_button = Button(root, text="转换", command=self.convert_excel_to_pdf)
  20. self.convert_button.pack()
  21. def choose_excel_folder(self):
  22. self.excel_folder_path = filedialog.askdirectory()
  23. self.label_excel.config(text="Excel文件夹路径: " + self.excel_folder_path)
  24. def choose_pdf_folder(self):
  25. self.pdf_folder_path = filedialog.askdirectory()
  26. self.label_pdf.config(text="PDF文件夹路径: " + self.pdf_folder_path)
  27. def convert_excel_to_pdf(self):
  28. if not self.excel_folder_path or not self.pdf_folder_path:
  29. print("请选择Excel和PDF文件夹路径")
  30. return
  31. # 遍历Excel文件夹中的所有文件
  32. for excel_file in os.listdir(self.excel_folder_path):
  33. if excel_file.endswith(".xlsx"):
  34. excel_path = os.path.join(self.excel_folder_path, excel_file)
  35. pdf_file = os.path.splitext(excel_file)[0] + ".pdf"
  36. pdf_path = os.path.join(self.pdf_folder_path, pdf_file)
  37. # 转换Excel到PDF
  38. self._convert_excel_to_pdf(excel_path, pdf_path)
  39. print("转换完成!")
  40. def _convert_excel_to_pdf(self, excel_path, pdf_path):
  41. # 读取Excel文件
  42. wb = load_workbook(excel_path)
  43. # 创建PDF文件
  44. pdf = canvas.Canvas(pdf_path)
  45. for sheet_name in wb.sheetnames:
  46. sheet = wb[sheet_name]
  47. for row in sheet.iter_rows():
  48. for cell in row:
  49. cell_value = str(cell.value)
  50. pdf.drawString(cell.column * 20, (sheet.max_row - cell.row) * 20, cell_value)
  51. pdf.save()
  52. if __name__ == "__main__":
  53. root = Tk()
  54. app = ExcelToPdfConverter(root)
  55. root.mainloop()

使用截图:

选择excel 存放的文件夹,再选择输出的文件夹。点击转换即可。只是为了实现功能,没有对界面过多的优化,后期再说。

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/笔触狂放9/article/detail/69498
推荐阅读
相关标签
  

闽ICP备14008679号