Python 操作office 封装

#coding=gbk

__author__ = ‘libo‘

import os

import time

import datetime

import traceback

from win32com.client import DispatchEx, constants, pythoncom

WORD_NAME = ‘result.docx‘  #默认的文件名称

EXCEL_NAME = ‘result.xlsx‘  #默认的文件名称

ISOTIMEFORMAT = ‘seop60_report%Y-%m-%d-%H_%M_%S‘

class Enum:

def __init__(self):

pass

xlColumnClustered = 51

class word:

def __init__(self, office_dir, name=WORD_NAME):

pythoncom.CoInitialize()

office_dir = office_dir.replace(‘/‘, ‘\\‘)

if office_dir[-1] != ‘\\‘:

office_dir += ‘\\‘

self.office_dir = office_dir  #word保存的文件夹

if not os.path.exists(office_dir):

os.makedirs(office_dir)

self.name = self.office_dir + time.strftime(ISOTIMEFORMAT, time.localtime()) + WORD_NAME  #最终保存的文件名

self.__app = DispatchEx(‘Word.Application‘)  # 挂载word程序

self.__app.Visible = False

self.__app.DisplayAlerts = False

self.__doc = self.__app.Documents.Add()  # 创建新的文档

self.__doc.SaveAs(self.name)

self.__excel = excel(self.office_dir)

def append_str(self, value, size=12, bold=0, alignment=0):

"""

添加文本到文档

"""

self.to_end()

self.__doc_range.InsertBefore(value+‘\n‘)

self.__doc_range.Select()

self.__doc_range.style = -1

self.__doc_range.Style.Font.Bold = bold

self.__doc_range.Style.Font.Size = size

self.__doc_range.ParagraphFormat.Alignment = alignment

self.__doc.Save()

def append_head_big(self, value):

"""

添加文本到文档

"""

self.to_end()

self.__doc_range.InsertBefore(value)

self.__doc_range.Select()

self.__doc_range.style = -2

self.__doc_range.ParagraphFormat.Alignment = 1

self.__doc_range.InsertAfter(‘\n‘)

self.__doc.Save()

def append_head(self, value):

"""

添加文本到文档

"""

self.to_end()

self.__doc_range.InsertBefore(value)

self.__doc_range.Select()

self.__doc_range.style = -3

self.__doc_range.ParagraphFormat.Alignment = 1

self.__doc_range.InsertAfter(‘\n‘)

self.__doc.Save()

def append_head_small(self, value):

"""

添加文本到文档

"""

self.to_end()

self.__doc_range.InsertBefore(value)

self.__doc_range.Select()

self.__doc_range.style = -4

self.__doc_range.ParagraphFormat.Alignment = 0

self.__doc_range.InsertAfter(‘\n‘)

self.__doc.Save()

def append_head_small_title(self, value):

"""

添加文本到文档

"""

self.to_end()

self.__doc_range.InsertBefore(value)

self.__doc_range.Select()

self.__doc_range.style = -5

self.__doc_range.ParagraphFormat.Alignment = 0

self.__doc_range.InsertAfter(‘\n‘)

self.__doc.Save()

def append_table(self, dyadic_array, x_len, y_len):

if len(dyadic_array) == 0:

return False

if x_len * y_len == 0:

return False

self.to_end()

tab = self.__doc.Tables.Add(self.__doc_range, x_len, y_len)

tab.Style = "网格型"  # 显示表格边框

for y_index in range(1, y_len + 1):

for x_index in range(1, x_len + 1):

tab.Cell(x_index, y_index).Range.Text = str(dyadic_array[x_index - 1][y_index - 1])

tab.Cell(x_index, y_index).Range.Font.Size = 10

self.__doc.Save()

return True

def append_chart(self, dyadic_array, x_len, y_len, chart_type, title, show_label=False):

if len(dyadic_array) == 0:

return False

if x_len * y_len == 0:

return False

self.append_head_small_title(title)

self.to_end()

self.__excel.insert_chart(dyadic_array, x_len, y_len, chart_type, title, show_label)

self.__doc_range.Paste()

#self.append_str(‘\n‘)

self.__doc.Save()

return True

def append_scatter(self, dyadic_array, x_len, y_len, title, x_axis=‘‘, y_axis=‘‘):

if len(dyadic_array) == 0:

return False

if x_len * y_len == 0:

return False

self.append_head_small_title(title)

self.to_end()

self.__excel.insert_Scatter(dyadic_array, x_len, y_len, title, x_axis, y_axis)

self.__doc_range.Paste()

self.append_str(‘\n‘)

self.__doc.Save()

return True

def to_end(self):

"""

移动到文档末尾

"""

self.__doc_range = self.__doc.Range()

self.__doc_range = self.__doc.Range(self.__doc_range.End - 1, self.__doc_range.End - 1)

self.__doc_range.Select()

self.__doc_range.style = -1

self.__doc_range.Style.Font.Bold = 0

self.__doc_range.Style.Font.Size = 12

self.__doc_range.ParagraphFormat.Alignment = 0

def un_init(self):

try:

if self.__doc:

self.__doc.Close()

if self.__app:

self.__app.Quit()

self.__app = None

except Exception:

self.__app.Quit()

finally:

self.__excel.un_init()

class excel:

def __init__(self, office_dir, name=EXCEL_NAME):

pythoncom.CoInitialize()

office_dir = office_dir.replace(‘/‘, ‘\\‘)

if office_dir[-1] != ‘\\‘:

office_dir += ‘\\‘

self.office_dir = office_dir  #EXCEL保存的文件夹

if not os.path.exists(office_dir):

os.makedirs(office_dir)

self.name = self.office_dir + time.strftime(ISOTIMEFORMAT, time.localtime()) + EXCEL_NAME  #最终保存的文件名

self.__app = DispatchEx(‘Excel.Application‘)  # 挂载word程序

self.__app.Visible = 0

self.__app.DisplayAlerts = 0

self.__book = self.__app.Workbooks.Add()  # 创建新的文档

self.__book.SaveAs(self.name)

def insert_chart(self, dyadic_array, x_len, y_len, chart_type, title, show_label=False, x_axis=‘‘, y_axis=‘‘):

if len(dyadic_array) == 0:

return False

if x_len * y_len == 0:

return False

title = unicode(title, ‘gbk‘).replace(‘*‘, ‘‘)

sheet = self.__book.Worksheets.Add()  # 增加新表,新表为第4个表,相当与wBook.Worksheets(4)

sheet.Name = title

print ‘_c_‘ + str(datetime.datetime.now())

for y_index in range(1, y_len + 1):

for x_index in range(1, x_len + 1):

sheet.Cells(x_index, y_index).Value = dyadic_array[x_index - 1][y_index - 1]

print ‘_d_‘ + str(datetime.datetime.now())

ra = sheet.Range(sheet.Cells(1, 1), sheet.Cells(x_len, y_len))

chart = self.__book.Charts.Add(pythoncom.Missing, sheet, pythoncom.Missing, pythoncom.Missing)

chart.ChartType = chart_type

chart.HasTitle = True

chart.ChartTitle.Text = title

if show_label:  #是否显示数据标签

if y_len == 1:

chart.SeriesCollection(1).ApplyDataLabels()

else:

for i in range(1, y_len):

chart.SeriesCollection(i).ApplyDataLabels()

chart.SetSourceData(ra)

if x_axis:

chart.SetElement(301)

chart.Axes(1, 1).AxisTitle.Text = x_axis

if y_axis:

chart.SetElement(310)

chart.Axes(2, 1).AxisTitle.Text = y_axis

chart.Location(2, title)  #这里可以独立出一个参数

sheet.ChartObjects(r"图表 1").Activate()

sheet.ChartObjects(r"图表 1").Copy()

self.__book.Save()

return True

def insert_Scatter(self, dyadic_array, x_len, y_len, title, x_axis=‘‘, y_axis=‘‘):

if len(dyadic_array) == 0:

return False

if x_len * y_len == 0:

return False

title = unicode(title, ‘gbk‘).replace(‘*‘, ‘‘)

sheet = self.__book.Worksheets.Add()  # 增加新表,新表为第4个表,相当与wBook.Worksheets(4)

sheet.Name = title

print ‘_a_‘ + str(datetime.datetime.now())

for y_index in range(1, y_len + 1):

for x_index in range(1, x_len + 1):

sheet.Cells(x_index, y_index).Value = dyadic_array[x_index - 1][y_index - 1]

print ‘_b_‘ + str(datetime.datetime.now())

ra = sheet.Range(sheet.Cells(1, 1), sheet.Cells(x_len, y_len))

chart = self.__book.Charts.Add(pythoncom.Missing, sheet, pythoncom.Missing, pythoncom.Missing)

chart.ChartType = -4169

chart.HasTitle = True

chart.ChartTitle.Text = title

chart.SeriesCollection(1).MarkerStyle = 8

chart.SeriesCollection(1).MarkerSize = 2

chart.SetSourceData(ra)

if x_axis:

chart.SetElement(301)

chart.Axes(1, 1).AxisTitle.Text = x_axis

if y_axis:

chart.SetElement(310)

chart.Axes(2, 1).AxisTitle.Text = y_axis

chart.Location(2, title)  #这里可以独立出一个参数

sheet.ChartObjects(r"图表 1").Activate()

sheet.ChartObjects(r"图表 1").Copy()

self.__book.Save()

return True

def un_init(self):

try:

if self.self.__book:

self.self.__book.Close()

if self.__app:

self.__app.Quit()

self.__app = None

except Exception:

self.__app.Quit()

if (__name__ == "__main__"):

try:

BASE_DIR = os.path.dirname(__file__)

w = word(BASE_DIR)

w.append_str(r‘插入测试‘)

dyadic_array = [[1, 2, 3], [4, 5, 6], [7, 8, 9], [7, 8, 9]]

w.append_table(dyadic_array, 4, 3)

w.append_chart(dyadic_array, 4, 3, 0, ‘title‘)

except Exception:

print traceback.format_exc()

finally:

w.un_init()

时间: 2024-08-02 17:58:11

Python 操作office 封装的相关文章

python 操作 office

http://www.cnblogs.com/youxin/p/3548647.html?utm_source=tuicool&utm_medium=referral 首先介绍下office win32 com接口,这个是MS为自动化提供的操作接口,比如我们打开一个WORD文档,就可以在里面编辑VB脚本,实现我们自己的效果.对于这种一本万利的买卖,Python怎么能放过,它内置了对于win32 com接口的支持,我们可以方便的控制. 要想熟练使用office win32 com接口,没有什么比M

python操作word、ppt的详解

python使用win32com的心得 python可以使用一个第三方库叫做win32com达到操作com的目的, 我是安装了ActivePython的第三方库,从官网下载了安装包,该第三方库几乎封装了所有python下面的win32相关的操作,例如win32api,win32gui等等,可以说是比较齐全的了,下载地址可以自行百度获取.         主要是有个项目可能要用到ppt转换成视频的功能. 之后在想使用com操作excel还有word,ppt的时候,相信大部分人跟我一样,都是搜索py

Python之路【第九篇】:Python操作 RabbitMQ、Redis、Memcache、SQLAlchemy

Python之路[第九篇]:Python操作 RabbitMQ.Redis.Memcache.SQLAlchemy Memcached Memcached 是一个高性能的分布式内存对象缓存系统,用于动态Web应用以减轻数据库负载.它通过在内存中缓存数据和对象来减少读取数据库的次数,从而提高动态.数据库驱动网站的速度.Memcached基于一个存储键/值对的hashmap.其守护进程(daemon )是用C写的,但是客户端可以用任何语言来编写,并通过memcached协议与守护进程通信. Memc

Python操作 RabbitMQ、Redis、Memcache、SQLAlchemy

Memcached Memcached 是一个高性能的分布式内存对象缓存系统,用于动态Web应用以减轻数据库负载.它通过在内存中缓存数据和对象来减少读取数据库的次数,从而提高动态.数据库驱动网站的速度.Memcached基于一个存储键/值对的hashmap.其守护进程(daemon )是用C写的,但是客户端可以用任何语言来编写,并通过memcached协议与守护进程通信. Memcached安装和基本使用 Memcached安装: wget http://memcached.org/latest

使用python操作mysql数据库

这是我之前使用mysql时用到的一些库及开发的工具,这里记录下,也方便我查阅. python版本: 2.7.13 mysql版本: 5.5.36 几个python库 1.mysql-connector-python 是MySQL官方的Python驱动 https://dev.mysql.com/doc/connector-python/en/ 安装: pip install mysql-connector 示例代码: https://github.com/mike-zhang/pyExample

Python操作Mysql基础教程

Python操作Mysql 最近在学习python,这种脚本语言毫无疑问的会跟数据库产生关联,因此这里介绍一下如何使用python操作mysql数据库.我python也是零基础学起,所以本篇博客针对的是python初学者,大牛可以选择绕道. 另外,本篇博客基于的环境是Ubuntu13.10,使用的python版本是2.7.5. MYSQL数据库 MYSQL是一个全球领先的开源数据库管理系统.它是一个支持多用户.多线程的数据库管理系统,与Apache.PHP.Linux共同组成LAMP平台,在we

Python面向对象编程-封装

1引言 你点击了桌面上的Chrome图标,一个浏览器窗口出现了,输入网址就可以在Internet世界愉快玩耍.这一切是怎么实现的呢?Chromium这个多进程的程序是如何启动各个进程的呢?浏览器主进程(界面进程)启动了哪些线程?如何启动的呢?这些问题一直萦绕在心头,一起来看看源代码吧.本文主要针对Chromium for Mac的源代码,其它操作系统大同小异. 2背景知识 浏览器作为一个应用程序,是以进程的形式运行在操作系统上的.首先,Chromium是一个多进程的应用程序,我们需要了解Chro

Python操作rabbitmq redis memcache SQLalchemy

Memcached Memcached 是一个高性能的分布式内存对象缓存系统,用于动态Web应用以减轻数据库负载.它通过在内存中缓存数据和对象来减少读取数据库的次数,从而提高动态.数据库驱动网站的速度.Memcached基于一个存储键/值对的hashmap.其守护进程(daemon )是用C写的,但是客户端可以用任何语言来编写,并通过memcached协议与守护进程通信. Memcached安装和基本使用 Memcached安装: 1 2 3 4 5 6 7 8 wget http://memc

python操作memcached以及分布式

memcached 是以 LiveJournal 旗下 Danga Interactive 公司的 Brad Fitzpatric 为首开发的一款软件.现在已成为 mixi.Facebook.LiveJournal 等众多服务中提高 Web 应用扩展性的重要因素. 许多 Web 应用都将数据保存到 RDBMS 中,应用服务器从中读取数据并在浏览器中显示.但随着数据量的增大.访问的集中,就会出现 RDBMS 的负担加重.数据库响应恶化.网站显示延迟等重大影响.这时就该 memcached 大显身手