python实现excel转换成pdf
1、安装
需要安装pywin32包,以实现对Office文件的操作,可以批量转换为pdf文件。支持 doc, docx, ppt, pptx, xls, xlsx 等格式。
pip install pywin32
2、office文件 (word, ppt, excel等) 转为pdf
#-*- coding:utf-8 -*-
import os
from win32com.client import Dispatch, constants, gencache, DispatchEx class PDFConverter:
def __init__(self, pathname, export='.'):
self._handle_postfix = ['doc', 'docx', 'ppt', 'pptx', 'xls', 'xlsx']
self._filename_list = list()
self._export_folder = os.path.join(os.path.abspath('.'), 'pdfconver')
if not os.path.exists(self._export_folder):
os.mkdir(self._export_folder)
self._enumerate_filename(pathname) def _enumerate_filename(self, pathname):
'''
读取所有文件名
'''
full_pathname = os.path.abspath(pathname)
if os.path.isfile(full_pathname):
if self._is_legal_postfix(full_pathname):
self._filename_list.append(full_pathname)
else:
raise TypeError('文件 {} 后缀名不合法!仅支持如下文件类型:{}。'.format(pathname, '、'.join(self._handle_postfix)))
elif os.path.isdir(full_pathname):
for relpath, _, files in os.walk(full_pathname):
for name in files:
filename = os.path.join(full_pathname, relpath, name)
if self._is_legal_postfix(filename):
self._filename_list.append(os.path.join(filename))
else:
raise TypeError('文件/文件夹 {} 不存在或不合法!'.format(pathname)) def _is_legal_postfix(self, filename):
return filename.split('.')[-1].lower() in self._handle_postfix and not os.path.basename(filename).startswith('~') def run_conver(self):
'''
进行批量处理,根据后缀名调用函数执行转换
'''
print('需要转换的文件数:', len(self._filename_list))
for filename in self._filename_list:
postfix = filename.split('.')[-1].lower()
funcCall = getattr(self, postfix)
print('原文件:', filename)
funcCall(filename)
print('转换完成!') def doc(self, filename):
'''
doc 和 docx 文件转换
'''
name = os.path.basename(filename).split('.')[0] + '.pdf'
exportfile = os.path.join(self._export_folder, name)
print('保存 PDF 文件:', exportfile)
gencache.EnsureModule('{00020905-0000-0000-C000-000000000046}', 0, 8, 4)
w = Dispatch("Word.Application")
doc = w.Documents.Open(filename)
doc.ExportAsFixedFormat(exportfile, constants.wdExportFormatPDF,
Item=constants.wdExportDocumentWithMarkup,
CreateBookmarks=constants.wdExportCreateHeadingBookmarks) w.Quit(constants.wdDoNotSaveChanges) def docx(self, filename):
self.doc(filename) def xls(self, filename):
'''
xls 和 xlsx 文件转换
'''
name = os.path.basename(filename).split('.')[0] + '.pdf'
exportfile = os.path.join(self._export_folder, name)
xlApp = DispatchEx("Excel.Application")
xlApp.Visible = False
xlApp.DisplayAlerts = 0
books = xlApp.Workbooks.Open(filename,False)
books.ExportAsFixedFormat(0, exportfile)
books.Close(False)
print('保存 PDF 文件:', exportfile)
xlApp.Quit() def xlsx(self, filename):
self.xls(filename) def ppt(self, filename):
'''
ppt 和 pptx 文件转换
'''
name = os.path.basename(filename).split('.')[0] + '.pdf'
exportfile = os.path.join(self._export_folder, name)
gencache.EnsureModule('{00020905-0000-0000-C000-000000000046}', 0, 8, 4)
p = Dispatch("PowerPoint.Application")
ppt = p.Presentations.Open(filename, False, False, False)
ppt.ExportAsFixedFormat(exportfile, 2, PrintRange=None)
print('保存 PDF 文件:', exportfile)
p.Quit() def pptx(self, filename):
self.ppt(filename) if __name__ == "__main__": # 支持文件夹批量导入
folder = 'tmp'
pathname = os.path.join(os.path.abspath('.'), folder) # 也支持单个文件的转换
# pathname = 'test.doc' pdfConverter = PDFConverter(pathname)
pdfConverter.run_conver()
转至https://blog.csdn.net/XnCSD/article/details/85208303
3、excel的不同sheet存为pdf
#-*- coding:utf-8 -*- import os
from win32com.client import Dispatch, constants, gencache, DispatchEx
import xlrd class PDFConverter:
def __init__(self, pathname,sheetnum, export='.'):
self.sheetnum = sheetnum
self._handle_postfix = ['doc', 'docx', 'ppt', 'pptx', 'xls', 'xlsx']
self._filename_list = list()
self._export_folder = os.path.join(os.path.abspath('.'), 'pdfconver')
if not os.path.exists(self._export_folder):
os.mkdir(self._export_folder)
self._enumerate_filename(pathname) def _enumerate_filename(self, pathname):
'''
读取所有文件名
'''
full_pathname = os.path.abspath(pathname)
if os.path.isfile(full_pathname):
if self._is_legal_postfix(full_pathname):
self._filename_list.append(full_pathname)
else:
raise TypeError('文件 {} 后缀名不合法!仅支持如下文件类型:{}。'.format(pathname, '、'.join(self._handle_postfix)))
elif os.path.isdir(full_pathname):
for relpath, _, files in os.walk(full_pathname):
for name in files:
filename = os.path.join(full_pathname, relpath, name)
if self._is_legal_postfix(filename):
self._filename_list.append(os.path.join(filename))
else:
raise TypeError('文件/文件夹 {} 不存在或不合法!'.format(pathname)) def _is_legal_postfix(self, filename):
return filename.split('.')[-1].lower() in self._handle_postfix and not os.path.basename(filename).startswith(
'~') def run_conver(self):
'''
进行批量处理,根据后缀名调用函数执行转换
'''
print('需要转换的文件数:', len(self._filename_list))
for filename in self._filename_list:
postfix = filename.split('.')[-1].lower()
funcCall = getattr(self, postfix)
print('原文件:', filename)
funcCall(filename)
print('转换完成!') def xls(self, filename):
'''
xls 和 xlsx 文件转换
'''
xlApp = DispatchEx("Excel.Application")
xlApp.Visible = False
xlApp.DisplayAlerts = 0
books = xlApp.Workbooks.Open(filename, False)
# 循环保存每一个sheet
for i in range(1, self.sheetnum+1):
sheetName = books.Sheets(i).Name
xlSheet = books.Worksheets(sheetName)
name = sheetName + '.pdf'
exportfile = os.path.join(self._export_folder, name)
xlSheet.ExportAsFixedFormat(0, exportfile)
print('保存 PDF 文件:', exportfile)
books.Close(False)
xlApp.Quit() def xlsx(self, filename):
self.xls(filename) if __name__ == "__main__":
# 支持单个文件的转换
pathname = u'原始数据.xlsx'
# 获取到文件的sheet数
b = xlrd.open_workbook(pathname)
sheetnum = len(b.sheets())
pdfConverter = PDFConverter(pathname, sheetnum)
pdfConverter.run_conver()
python实现excel转换成pdf的更多相关文章
- 多页Excel转换成PDF时如何保存为单独文件
通过ABBYY PDF Transformer+图文识别软件,使用PDF-XChange打印机将多页Excel工作簿转换成PDF文档(相关文章请参考ABBYY PDF Transformer+从MS ...
- excel 转换成pdf 总结
excl 转换成pdf 1.freespire 只能转换前三页 // 使用此组件 只能转换前3页 //需要引用 如下命名空间 //using Spire.Doc; //Document doc = ...
- Excel转换成PDF
public class Office2Pdf { public bool DOCConvertToPDF(string sourcePath, string targetPath) { //Stre ...
- python 将excel转换成字典,并且将字典写到txt文件里
# -*- coding: utf-8 -*- #python2.7 import sys reload(sys) sys.setdefaultencoding('utf-8') from pyexc ...
- word ppt excel文档转换成pdf
1.把word文档转换成pdf (1).添加引用 using Microsoft.Office.Interop.Word; 添加引用 (2).转换方法 /// <summary> /// ...
- Python 爬虫:把廖雪峰教程转换成 PDF 电子书
写爬虫似乎没有比用 Python 更合适了,Python 社区提供的爬虫工具多得让你眼花缭乱,各种拿来就可以直接用的 library 分分钟就可以写出一个爬虫出来,今天尝试写一个爬虫,将廖雪峰老师的 ...
- C#.net word excel powerpoint (ppt) 转换成 pdf 文件
using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using Sy ...
- C#实现文档转换成PDF
网上有很多将doc.ppt.xls等类型的文档转换成pdf的方法,目前了解到的有两大类: 1.使用虚拟打印机将doc.ppt.xls等类型的文档 2.使用OFFICE COM组件 我采用了第二种方法实 ...
- c# office转换成pdf
下载地址 [url]http://www.microsoft.com/downloads/details.aspx?FamilyId=4D951911-3E7E-4AE6-B059-A2E79ED87 ...
随机推荐
- Windows 环境下安装redis 及其PHP Redis扩展
1.安装Redis (1)这里选择在github官网上下载Redis,地址:Redis下载地址 下载压缩包(如下图),并解压到本地目录,我放在D:\redis (2)验证Redis安装是否成功打开命令 ...
- Spark-Streaming获取kafka数据的两种方式:Receiver与Direct的方式
简单理解为:Receiver方式是通过zookeeper来连接kafka队列,Direct方式是直接连接到kafka的节点上获取数据 Receiver 使用Kafka的高层次Consumer API来 ...
- egon说一切皆对象--------面向对象进阶紫禁之巅
一.检查isinstance(obj,cls)和issubclass(sub,super) class Foo(object): pass obj = Foo() isinstance(obj, Fo ...
- [转载]转一篇Systemverilog的一个牛人总结
原文地址:转一篇Systemverilog的一个牛人总结作者:dreamylife Systemverilog 数据类型 l 合并数组和非合并数组 1)合并数组: 存储方式是连续的,中间没 ...
- 用户在浏览器输入URL或者跳转到一个URL后发生了什么
一.从URL到页面渲染的整个过程1)处理用户输入2)开始导航3)读取响应4)查找渲染进程5)确认导航6)渲染页面 二.每一步做了哪些事情 1)处理用户的输入 浏览器的UI 线程处理用户的输入,判断是跳 ...
- 安装SQL2005数据库服务时报错处理方法
运行一个脚本,以管理员身份运行: net stop winmgmt c: cd %systemroot%/system32/wbem rd /S /Q repository regsvr32 /s % ...
- 机器学习分类算法之K近邻(K-Nearest Neighbor)
一.概念 KNN主要用来解决分类问题,是监督分类算法,它通过判断最近K个点的类别来决定自身类别,所以K值对结果影响很大,虽然它实现比较简单,但在目标数据集比例分配不平衡时,会造成结果的不准确.而且KN ...
- 与Swing的初见
---------------------------参考菜鸟教程的swing课程学习-------------------- Swing 是一个为Java设计的GUI工具包. Swing是JAVA基 ...
- 【leetcode】Reaching Points
题目如下: A move consists of taking a point (x, y) and transforming it to either (x, x+y) or (x+y, y). G ...
- C# 实现二维数组的排序算法(代码)
class Order { /// <summary> /// 对二维数组排序 /// </summary> /// <param name="values&q ...