赞
踩
#创作灵感 前一阵有很多粉丝关注到之前的一篇文章,关于用VBS脚本批量将Word转换为PDF文件,有粉丝私信我,有没有excel转换pdf的,网上查了一些VBS脚本,似乎没有能用的,我就用python编写了一个脚本,测试没什么问题。
脚本如下:
- import os
- from tkinter import Tk, Label, Button, filedialog
- from openpyxl import load_workbook
- from reportlab.pdfgen import canvas
-
- class ExcelToPdfConverter:
- def __init__(self, root):
- self.root = root
- self.root.title("Excel to PDF Converter")
-
- self.excel_folder_path = ""
- self.pdf_folder_path = ""
-
- self.label_excel = Label(root, text="Excel文件夹路径:")
- self.label_excel.pack()
-
- self.button_excel = Button(root, text="选择Excel文件夹", command=self.choose_excel_folder)
- self.button_excel.pack()
-
- self.label_pdf = Label(root, text="PDF文件夹路径:")
- self.label_pdf.pack()
-
- self.button_pdf = Button(root, text="选择PDF文件夹", command=self.choose_pdf_folder)
- self.button_pdf.pack()
-
- self.convert_button = Button(root, text="转换", command=self.convert_excel_to_pdf)
- self.convert_button.pack()
-
- def choose_excel_folder(self):
- self.excel_folder_path = filedialog.askdirectory()
- self.label_excel.config(text="Excel文件夹路径: " + self.excel_folder_path)
-
- def choose_pdf_folder(self):
- self.pdf_folder_path = filedialog.askdirectory()
- self.label_pdf.config(text="PDF文件夹路径: " + self.pdf_folder_path)
-
- def convert_excel_to_pdf(self):
- if not self.excel_folder_path or not self.pdf_folder_path:
- print("请选择Excel和PDF文件夹路径")
- return
-
- # 遍历Excel文件夹中的所有文件
- for excel_file in os.listdir(self.excel_folder_path):
- if excel_file.endswith(".xlsx"):
- excel_path = os.path.join(self.excel_folder_path, excel_file)
- pdf_file = os.path.splitext(excel_file)[0] + ".pdf"
- pdf_path = os.path.join(self.pdf_folder_path, pdf_file)
-
- # 转换Excel到PDF
- self._convert_excel_to_pdf(excel_path, pdf_path)
-
- print("转换完成!")
-
- def _convert_excel_to_pdf(self, excel_path, pdf_path):
- # 读取Excel文件
- wb = load_workbook(excel_path)
-
- # 创建PDF文件
- pdf = canvas.Canvas(pdf_path)
-
- for sheet_name in wb.sheetnames:
- sheet = wb[sheet_name]
-
- for row in sheet.iter_rows():
- for cell in row:
- cell_value = str(cell.value)
- pdf.drawString(cell.column * 20, (sheet.max_row - cell.row) * 20, cell_value)
-
- pdf.save()
-
- if __name__ == "__main__":
- root = Tk()
- app = ExcelToPdfConverter(root)
- root.mainloop()
使用截图:
选择excel 存放的文件夹,再选择输出的文件夹。点击转换即可。只是为了实现功能,没有对界面过多的优化,后期再说。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。