python写的excel排页程序
朋友搞工程,需要对大量的excel文件进行排页,就像下图,当有每多个文件,并且每个文件中有很多的sheet的时候,排页码的工作量就很大了。
用python去帮开发一个小工具,一开始选择用xlrd和xlwt去实现,可是后来测试发现在写文件的时候会改变之前原有的样式,查了很多资料也没有太好的解决方案,又试了用openpyxl,也发现会有样式问题。
最后实在没有办法,只能使用最挫最笨的方案了,就是使用win32com,去调用excel的api。。。如果有好的解决方案可要告诉我哈。
- 上代码
#!usr/bin/python
# -*- coding: utf-8 -*-
import os
import sys
import win32com.client
import types
import datetime
reload(sys)
sys.setdefaultencoding('utf8')
def dirFolder(path, pageBeginNum):
_filelist = os.listdir(path)
#建立临时文件夹
now = datetime.datetime.now()
tmpPath = now.strftime('%Y-%m-%d-%H-%M-%S')
os.mkdir(tmpPath)
tmpPath = os.path.abspath(tmpPath)
tmpPath = unicode(tmpPath, 'gbk')
xlApp = win32com.client.Dispatch('Excel.Application')
for filename in _filelist:
filepathname = os.path.abspath(path+os.path.sep+filename)
if os.path.isdir(filepathname):
error("输入文件夹中包含子文件夹 : %s"%filepathname)
else:
#打开文件,获取工作表列表
if not os.path.isfile(filepathname):
error("不是文件" + filepathname)
info(os.path.abspath(filepathname))
xlBook = xlApp.Workbooks.Open(r''+filepathname)
worksheets = xlBook.Worksheets
for sheet in worksheets:
if(sheet.Visible):
sheet.PageSetup.CenterFooter= ("第" + str(pageBeginNum) + "页").decode('UTF-8')
sheet.PageSetup.FooterMargin=0.9/0.035
pageBeginNum += 1
xlBook.SaveAs((tmpPath + os.path.sep + filename).decode('UTF-8'))
#xlBook.Save()
xlBook.Close(SaveChanges=1)
xlApp.Application.Quit()
xlApp=0
del xlApp
def error(msg):
print "error : " + msg.decode('UTF-8')
exit(0)
def info(msg):
print "info : " + msg.decode('UTF-8')
if __name__=='__main__':
if(len(sys.argv) == 3):
try:
pageBeginNum = int(sys.argv[2])
tplFile = unicode(sys.argv[1], 'gbk')
except:
error("开始页码数必须是数字!!")
if(not os.path.isdir(tplFile)):
error("第一个参数必须是一个文件夹!!")
if type(pageBeginNum) is types.IntType or isinstance(pageBeginNum,int):
dirFolder(tplFile, pageBeginNum)
else:
error("请输入排序文件夹及开始页码数!!")
- 代码写的急,也没考虑优化、架构啥的,欢迎大家吐槽啊
- 以下是打包代码
#-*-coding: UTF-8-*-
from distutils.core import setup
import py2exe
# Powered by ***
INCLUDES = []
options = {"py2exe" :
{"compressed" : 1,
"optimize" : 2,
#"bundle_files" : 1,
"includes" : INCLUDES,
"dll_excludes": [ "MSVCP90.dll", "mswsock.dll", "powrprof.dll","w9xpopen.exe"] }}
setup(
options = options,
description = "excel自动编页系统",
zipfile=None,
console=[{"script": "excel自动编页系统.py", "icon_resources": [(1, "logo.ico")]}]
)
- 后期想重构一下变成UI的,等有时间再弄吧。。。。。