Python对Excel操作详解.docx

Python对Excel操作详解.docx
Python对Excel操作详解.docx

Python 对 Excel 操作

详解

文档摘要:

本文档主要介绍如何通过 python 对OffiCe excel 和Xlutils

模块。另外还演示了如何通过

Tcl tcom 包对excel 操作。

关键字:

PythOn 、Excel 、xlrd 、xlwt 、xlutils

进行读写操作,使用了 Xlrd 、XlWt

、TCl 、tcom

1 Python 简介

PythOn是一种面向对象、直译式电脑编程语言,具有近二十年的发展历史,成熟且稳定。它包含了一组完善而且容易理解的标准库,能够轻松完成很多常见的任务。它的语法简

捷和清晰,尽量使用无异义的英语单词,与其它大多数程序设计语言使用大括号不一样,它

使用縮进来定义语句块。

与SCheme Ruby、Perl、TCl等动态语言一样,Python具备垃圾回收功能,能够自动管理存储器使用。它经常被当作脚本语言用于处理系统管理任务和网络程序编写,然而它也

非常适合完成各种高级任务。PythOn虚拟机本身几乎可以在所有的作业系统中运行。使用

一些诸如py2exe、PyPy、PyInstaller 之类的工具可以将PythOn源代码转换成可以脱离

Python解释器运行的程序。

2 Python 安装

PythOn目前的版本已经更新到3.4.0 ,本文使用的版本为2.7.5 ,所有的版本都可以在python官网https://www.360docs.net/doc/f76074760.html,∕下载,至于2.x和3.x版本的具体区别也可以在官

网查看。

从官网下载了PythOn 2.7.5 安装文件Pyth On-2.7.5.msi 后,直接双击就可以安装

python 了,可以选择安装路径,我改为了,然后一路next就完成安装了,

安装完成后在C盘下就多了一个文件夹Python2.7.5。

PythOn也是一种实时交互语言,可以通过自带的IDLE编写python语句并反馈回显信

息,可以通过图1方式调出python IDLE。

Spirent C?n∣nUniCitiOnS U TF-IJMK

)WlnPCaP

*s Module Decs *j FythOn

(eor?m?ιιd IirLeJ /

WireShark国1FythOil Γlanιι?lΞ ]所有程序¢) * ? Pjrthg 2. 7UTIlnstall Fythein

>L远程桌面连接

也可以在Cmd 下输入Python ,但默认情况下 Python 并没有添加到 Windows 环境变量 中,导致在Cmd 下输入PythOn 的时候出现提示“ 'python'

不是内部或外部命令, 也不是可

运行的程序或批处理文件。”,windows 下可执行文件在运行时首先在当前目录下搜索,因为 进入Cmd 下默认路径一般为

C:\Documents and Settings ?Administrator>

,而在这个路径

下是找不到PythOn 的,所以提示出错,可以进入到 PythOn 安装目录下,然后执行

PythOn

就可以进入交互命令行模式下。如果懒的每次都进入 PythOn 安装,此时需要将PythOn 安装 路径添加到系统变量中,然后Windows 在执行命令的时候会去环境变量中查找路径, 具体配

置如图2所示,在Path 中添加PythOn 的安装路径“C:\Python2.7.5; ”,主要路径后面要

加”;”

常规 计算机名』硬件

要讲行大冬数改动I 燃必须件

I

环境变星通)I

错俣報告⑥

P ---------------------------------------------

分号表面这是一个路径的结束, 此时无论在哪个路径下都可以执行

PythOn 调出交互命令行。

i??S

性能

观觉效果」处理器计划I 内存使用

新建

(?)

用户配青丈件

与您登录有关的臺面役置

启动和故睦恢复

系统启动I 系统失败和调试信息

仝 ≡

f: ?Pγtho∏rτ 5 ; E : ?TCIAbin 工:?TlU COM : EXE : BAT : CMD : TOS : VBE;

..9G

≡fi

Frjro-JDST_C. .. WO

i∏?五JJF 五…2 OS 1?iruiMs HT P?THEXf 图2

3 Python语法入门

在Python 简介中提到Python 是一种直译式电脑编程语言,体现在语法中,如要将变

量a 赋值为1,TCl 使用命令%set a 1 (本文中为了区分 TCl 和Python 的命令,TCl 命令前 会加上"%',否则默认为 PythOn 命令),在PythOn 中命令为a = 1 ,输出a 的值可以直接 输入a ,也可以通过Print 语句输出a 的值,命令为Print a (在PythOn 3.0 以后版本中, Print 不再是一个语句,而是一个函数,所以如果想要输出 中求1和10的和或者变量之间的加减乘除运算需要使用 达式就可以了,如图 3所示。

?> >? 钛≡

1

a

?> L ?a "t, T.Z &

?> b ■

10

?>

SL-E

?> 10 a*b

?> LQl ?>

ID* Io-Io/10 如果对某个函数的作用不了解,可以通过 help 函数查看,如help (math.pow )

本文只是带领大家入门,PythOn 的其他语法可以参考其它资料学习。

a ,用法为 Print(a))。在 Tcl expr 命令,在Python 则直接写表

PythOn 很多功能都是靠模块实现的,比如 ftplib 模块负责ftp 功能的实现,math 模

块囊括了基本数学公式,如果我们想要引用这些模块,需要使用命令 import 模块名称,如 import ftplib 和import math 。如果想使用

math 模块中的函数

floor ,可以使用命令 math.floor (28.5) ,语法为"模块.函数”,如果想要直接使用 floor

函数,必须提前引用,

命令为from math import floor ,那样就可以直接使用命令

floor(28.5) TO 如果觉得 floor

这个函数名称太长了或者不好记忆,可以通过变量引用函数,如 f = math.floor

,这样变

量f 就充当了 math.floor 的功能了。上面提到的模块ftplib 和math 都是在python 安装的 时候已经安装了, 而接下来重点介绍的 Xlrd 、XlWt 、xlutils

模块都不是随PythOn 安装的。

需要手动下载安装,第 5节会详细介绍模块的安装。

当成功导入了某个模块后,可以通过函数

dir (模块名)查看这个模块包含哪些函数,

4 Tcl对Excel操作

在使用Python对excel操作之前搜索过如何通过TCl对excel操作,TCl本身没有提

供对excel操作的命令,可以通过tcom外部包来调用excel的接口实现,但是个人感觉实

现起来比较麻烦,msdn网站上虽然提供了excel的接口,但示例都是针对VB脚本语言写的,Tcl如果想要调用的话还需要转换,如下是一段简单的Tcl代码展示如何通过tcom对excel

进行操作,但也花了本人不少时间琢磨。

#加载tcom包

PaCkage require tcom

Set file name "F:/1.xls"

#创建com实例,打开工作表,下面四句都是套路

Set excel [::tcom::ref CreateObjeCt "Excel.Applicati on"]

Set workbooks [$excel Workbooks]

Set workbook [$WorkbookS OPen $fiIe name]

Set WOrkSheetS [$workbook Worksheets]

# "sheet1"为Sheet 的名称

Set WOrkSheet [$WOrkSheetS Item "sheet1"]

#创建单元格对象

Set cells [$WOrkSheet Cells]

#给单元格B2赋值为“ hsdf ”

$cells Item 2 B "hsdf"

#获取Sheet的个数并赋值给SheetCOUnt

Set SheetCO Un t [$WOrkSheetS Count]

#获取A1至A15单元的范围对象

Set range [$WOrkSheet Range A1 A15]

#给A1至A15单元赋值

$range Value2 "abcdefg"

#获取A1至A15的值,并赋值给A,A是一个列表list

Set A [$range Value2]

#设置单元的背景色

Set in terior [$ra nge In terior]

$in terior Color [expr 0x00FFE0]

#设置单元的前景色和字体大小、加粗、斜体、字体

Set fon t [$ra nge Font]

$font Color [expr OXFFoo00]

$font Bold 1

$font SiZe 10

$font ItaIiC 0

$font Name "华文行楷"

#设置单元格的宽度为自动调整

Set en tire [$ra nge En tireColu mn]

$en tire AUtOFit

#保存文档

$Workbook SaVe

#显示Excel

$excel ViSibIe 1

5 xlwt和口xlrd模块的安装

Python也是通过导入外部模块来实现对excel的操作,Xlrd负责对excel的读取,xlwt

负责对excel的写入,xlutils 依赖于Xlrd和xlwt,可以复制excel文件。这三个包都可以在网站http://www.pyth。https://www.360docs.net/doc/f76074760.html,/ 下载。本文使用的xlrd 版本为0.8.0 ,xlwt版本

为0.7.5。从网上下载好xlrd和xlwt后,解压缩到C:\PythOn2.7.5?Lib 下,此时在命令

行下输入import xlrd 或者import xlwt,会出现提示ImportError: No module namedxlwt ,这表明还没有安装xlwt模块。

python导入一个模块的过程要求有一个叫做“路径搜索”的操作过程,即是在文件系

统“预先设定的区域”查找模块文件以加载模块的过程。这个预先设定的区域其实是PythOn

搜索路径的一组目录。这个目录保存在sys.path中,如果你想知道PythOn导入模块时会在哪些路径搜索模块,你可以执行以下命令查看搜索路径目录:

>>> import SyS

>>> SyS.path

[DWpytho n??shell?? 2.7.5',C??Pytho n2.7.5??Lib??idlelib',C??Pytho n2.7.5??l

ib??site-packages??setuptools-1.3-py2.7.egg',C??Pytho n2.7.5??lib??site-packag

es??xlutils-1.7.0-py2.7.egg',C??Wi ndows??system32??pytho n27.zip',C??Pyth

on2 .7.5??DLLs',C??Pytho n2.7.5??lib',C??Pytho n2.7.5??lib??plat-wi n', CWPytho n2.7.5??lib??lib-tk',C??Pytho n2.7.5',C??Pytho n2.7.5??lib??site-pa CkageS','C:\\Pytho n2.7.5??lib??site-packages??wi n32',C??Pyth on 2.7.5??lib??sit e-packages??wi n32??lib',C??Pytho n2.7.5??lib??site-packages??Pytho nwin'] 在sys.path中找到一个路径为CWPython2.7.5??lib' ,所以我们把模块解压缩到这

个目录下。命令>>>sys.path.appe nd(C??Pytho n2.7.5??lib') 在最后添加一个目录,sys.path.i nsert(O,' C:\\Pytho n2.7.5??lib ') 在第一位插入一个目录。

解压缩完成并放在正确目录后,在Cmd下进入PaCkage当前目录,然后输入命令

“ C:\Pyth On 2.7.5?Lib?xlrd-0.8.0>python setup.py in stall ”,安装完成后可以输入import xlrd ,dir(xlrd) 来确认是否已经安装正确。

6 xlrd简单使用方法

>>>import xlrd

>>>excel = Xlrd.open_workbook("C:\Users\HuZha ngdo ng?Desktop?ASB 测试床环境信息

图.xls") #打开文件并将对象存储到excel中

>>>sheet = excel.sheet_by_index(0) #通过索引读取Sheet 对象,第一个Sheet 的索引为"0"

>>>row 3 = sheet.row VaIUeS(2) #读取第3行的所有数据,并以列表的形式存储到row 3 中

>>>col_3 = sheet.col_VaIUeS(2) # 读取第col_3 中

>>>cell_12_7 = sheet.CeILValUe(11,6)

cell_12_7 中

>>>cell_11_11 = sheet.cell(10,10).value

cell_11_11 中

>>>cell_7_8 = sheet.row(6)[7].value 3列的所有数据,并以列表list的形式存储到#读取第12行第7列的数据,并存储到

#读取第11行第11列的数据,并存储到

#读取第7行第8列的数据

#读取第8列第7行的数据

基本上面的命令已经可以满足目前对 excel 读取的操作了,接下给大家讲解XlWt 的用

法。

7 Xlwt 简单使用方法

import os,xlwt,datetime # 导入模块

style2 = xlwt.XFStyle() style3 = xlwt.XFStyle()

#设置字体格式 font1 = xlwt.Font()

#创建 font1

https://www.360docs.net/doc/f76074760.html, = 'Times NeW Roman' # 字体为'Times NeW Roman'

fon t1.bold = TrUe

# 加粗

fon t1.colour_i ndex = 2 # 字体颜色为红色, 0 = Black, 1 = White, 2 = Red, 3 = Gree n,

4 = Blue,

5 = Yellow,

6 = Mage nta,

7 = Cya n font1.underline

= xlwt.FOnt.UNDERLINE_DOUBLE # 下划线类型, UNDERLINE_DOUBL 代表

双下戈U 线,另 外还有 UNDERLINE_NONEUNDERLINE_SINGLE, UNDERLINE_SINGLE_ACC, UNDERLINE_DOUBLE, UNDERLINE_DOUBLE_ACC

fon t1.escapeme nt = xlwt.F On t.ESCAPEMENT_SUPERSCRIPT # 设置上标 fon t1.family = xlwt.Fo nt.FAMILY_ROMAN

font1.height =

0x190 #0x190是16进制,换成10进制为400 ,然后除以20,就得到字体

>>>nu m_rows = sheet. nrows >>>nu m_cols = sheet. ncols

#读取Sheet 的总行数

#读取Sheet 的总列数

#-*- coding: UTF-8 -*-

#设置编码格式为 utf-8

data =xlwt.Workbook() #新建一个 Workbook

Sheet = data.add_Sheet(U"sheet") #新建一个Sheet ,名称为'sheet'

style1 = xlwt.XFStyle()

#创建格式style1

style1.font = font1 #将创建的font1 字体格式应用到style1 上

font2 = xlwt.Fo nt() #创建font2

fon t2. name = "Algeria

# 字体为'Algerian'

n"

fon t2.colo ur_in dex = 3 #字体颜色为绿色

fon t2.italic = TrUe #斜体

fon t2.struck_out = TrUe #删除线

fon t2.height = 0x258 #字体大小为30

style2.fo nt = font2 #将创建的font2字体格式应用到style2 上

#设置列宽

sheet.col(0).width = 6000

sheet.col(1).width = 12000

Sheet.set_CoLdefault_width(2)

#设置单元格对齐方式

alignment = xlwt.Alignment() #创建alignment

alignment.horz = xlwt.Alignment.HORZ_CENTER #设置水平对齐为居中,May be:

HORZ_GENERAL, HORZ_LEFT, HORZ_CENTER, HORZ_RIGHT, HORZ_FILLED, HORZ_JUSTIFIED, HORZ_CENTER_ACROSS_SEL, HORZ_DISTRIBUTED

alignment.vert = xlwt.Alignment.VERT_CENTER #设置垂直对齐为居中,May be:

VERT_TOP, VERT_CENTER, VERT_BOTTOM, VERT_JUSTIFIED, VERT_DISTRIBUTED

style3.alignment = alignment # 应用alignment 至U style3 上

#插入时间

style3. num _format_Str = 'YYYY-MM-DD HH:MM:SS' # 设置时间格式

sheet.write(1,1,datetime.datetime. no w(),style3) #在第2行第2列插入当前时间,

#设置单元格背景颜色 Pattern_yellow = xlwt.Pattern()

#仓U 建 Pattern_yellow

Pattern_yellow.pattern = xlwt .P attern.SOLID_PATTERN # 设置填充模式为全部填充

Pattern_yellow.pattern_fore_colour = 5 #设置填充颜色为 yellow 黄色

style1.pattern = Pattern_yellow # 把设置的 Pattern 应用到 style3 上

Pattern_red = xlwt.Pattern()

#创建 Pattern_red

Pattern_red.pattern = xlwt.Pattern.SOLID_PATTERN # 设置填充模式为全部填充

Pattern_red.pattern_fore_colour = 2 #设置填充颜色为 red 红色

style2.pattern = Pattern_red

# 把设置的 Pattern 应用到 style4 上

#设置单元格边框

borders.left = xlwt.Borders.DASHED #设置左边框的类型为虚线

May be: NO_LINE, THIN,

MEDIUM, DASHED, DOTTED, THICK, DOUBLE, HAIR, MEDIUM_DASHEDTHIN_DASH_DOTTED, MEDIUM_DASH_DOTTED,

THIN_DASH_DOT_DOTTED,

MEDIUM_DASH_DOT_DOTTED,

SLANTED_MEDIUM_DASH_DOTTED, or OxOO through 0x0D. borders.right = xlwt.Borders.THIN borders.top = xlwt.Borders.DOTTED borders.bottom = xlwt.Borders.THICK

borders = xlwt.Borders()

# 创建 borders

#设置右边框的类型为细线 #设置上边框的类型为打点的 #设置底部边框类型为粗线

borders .left colour = 0x10 #设置左边框线条颜色

borders.right_colour = 0x20 borders.top_colour = 0x30 borders.bottom_colour = 0x40 style1.borders = borders style2.borders = borders

#将borders 应用到style1 上 #将borders 应用到style2 上

sheet.write(3, 0, 'HuZha ngdo ng', style1) 式引用style1

sheet.write(4, 0, 'Yi nMengran' , style2) 标

#在第4行第1列写入'HuZhangdong',格

#在第5行第1列写入'YinMengran',格式

引用Style2

data.save(u'e:\\3.xls') #保存到e:\\3.xls

函数xlwt.Workbook() 只能新建一个excel文档,不能打开一个已经存在的文档,下一章会讲解如何通过xlutils 修改一个已经存在的excel文档。

8 Xlutils 简单使用方法

本章将讲解如何使用Xlutils 编辑一个已经存在的文档,需要导入Xlutils 模块,下载地址是https://www.360docs.net/doc/f76074760.html,/ ,模块成功安装后就开始编写脚本吧。

#-*- Codi ng:utf-8 -*- #设置当前编码格式为utf-8

import xlwt #导入xlwt 模块

import xlrd #导入xlrd 模块

from xlutils.copy import copy # 导入import 模块的copy函数,接下来就可以直

接使用函数copy TO

fileName = "E:\\4.xls"

SheetName = "sheet1"

StyIeBoldRed = xlwt.easyxf('fo nt: color- in dex red, bold on') # 设置字体,颜色为红色,加粗

oldWb = xlrd.open_workbook(fileName, formatting_info=True) # 使用Xlrd.open_workbook 函数打开文件,formatt ing」n fo=True 表示保留该文件的格式newWb = copy(oldWb) #通过copy 函数把OldWb copy 至U newWb 然后通过编辑newWb来实现编辑已经存在的文件。

newWs = newWb.get_Sheet(0) #读取第一个Sheet

newWs.write(4, 0, "ValUe1",StyleBoldRed) #第5行第1列写入值"value1 ”,格式采用StyIeBoldRed 。

n ewWs.write(4, 1, "value2",styleBoldRed) #第5行第2列写入值"value2

newWs.write(4, 2, "value3",styleBoldRed) #第5 行第3 列写入值"VaIUe3 newWb.save(fileName) # 文件保存为"E:\\4.xls"

python用win32com处理excel表格

1. Python 操作 Excel 的函数库 我主要尝试了 3 种读写 Excel 的方法: 1> xlrd, xlwt, xlutils: 这三个库的好处是不需要其它支持,在任何操作系统上都可以使用。 xlrd 可以读取 .xls, .xlsx 文件,非常好用;但因为 xlwt 不能直接修改 Excel 文档,必须得复制一份然后另存为其它文件,而且据说写复杂格式的 Excel 文件会出现问题,所以我没有选它来写 Excel 文件。 2> openpyxl: 这个库也是不需要其它支持的,而且据说对 Office 2007 格式支持得更好。 遗憾地是,我经过测试,发现它加载 Excel 文件的效率比 xlrd 慢 3 倍以上,内存使用在 10 倍以上,于是就放弃了。 3> win32com: Python Win32 扩展,这个库需要运行环境为 Windows+Office 对应版 本。由于 Python Win32 扩展只是把 COM 接口包装了一下,可以视为与 VBA 完全相同,不会有读写格式上的问题。尝试了一下用 win32com 读取 Excel 文件,效率还是比 xlrd 慢一些。 由于读取效率上 xlrd > win32com > openpyxl,所以我自然选择了 xlrd 用来读取统计报表;而最终输出的报表格式较复杂,所以选择了 win32com 直接操作 Excel 文件。 2. Python 里的关系型数据库 SQLite是一个非常轻量级的关系型数据库,很多语言和平台都内置 SQLite 支持,也是 iOS 和Android 上的默认数据库。Python 的标准库里也包含了sqlite3库,用起来非常方便。 3. 用 xlrd 读取 Excel 并插入数据库样例 如果数据量不大,直接用 Python 内部数据结构如 dict, list 就够了。但如果读取的几张表数据量都较大,增加个将数据插入数据库的预处理过程就有很大好处。一是避免每次调试都要进行耗时较长的 Excel 文件载入过程;二是能充分利用数据库的索引和 SQL 语句强大功能进行快速数据分析。 #!/usr/bin/python # -*- coding: gbk -*- import xlrd import sqlite3 # 打开数据库文件 device_city_db = sqlite3.connect('device_city.db') cursor = device_city_db.cursor() # 建表 cursor.execute('DROP TABLE IF EXISTS device_city') cursor.execute('CREATE TABLE device_city (device_id char(16) PRIMARY KEY, city varchar(16))') # 打开 device 相关输入 Excel 文件 device_workbook = xlrd.open_workbook('输入.xlsx')

教你在python在工作中“偷懒”:Excel自动化处理 word关键信息提取 自动化运营监控 自动发送邮件

教你用python在工作中“偷懒” Excel自动化处理/word关键信息提取/自动化运营监控/自动发送邮件 有些朋友在工作中会有这样的困惑:明明我从早忙到晚,为什么得到的评价还不高? 要知道,企业对一个员工的评价是出于“产出”而非“付出”。所以,如果把大量时间花在机械重复的工作上,不但工作效率不高,对个人发展来说也无甚帮助。 而这些工作,如果对于会点编程的人来说,往往通过几行代码就可以快速搞定了。 于是,我去了解了一下身边不同岗位(HR、产品、运营、市场、数据分析师等)每天需要面对的重复性劳动(肯定会有不全,欢迎补充~),总结了一些在工作中非常常见的例子,并且将源码整理好供参考。希望这些程序可以让你的工作更高效!(升职加薪了别忘了回来发红包哦~)那么如何将这些统统实现呢? 我将这些分为以下几类,大家可以自行评估,各取所需:

如何用python在工作中“偷懒”? 系统录入自动化 由于你经常需要不断的将一些信息录入系统,每一次录入的过程中你可能需要不断的点击一些按钮,面对这种情况,完全可以写一个自动脚本,每次代替你来执行这些点击的行为。

这里我们需要用到splinter: pip install splinter 这里写了一个自动登录邮箱的脚本,可以实现文本输入和网页点击:#coding=utf-8import timefrom splinter import Browserdef splinter(url): browser = Browser() #login 126 email websize browser.visit(url) #wait web element loading time.sleep(5) #fill in account and password browser.find_by_id('idInput').fill('xxxxxx') browser.find_by_id('pwdInput').fill('xxxxx') #click the button of login browser.find_by_id('loginBtn').click() time.sleep(8) #close the window of brower browser.quit()if __name__ == '__main__' splinter(websize)

pythonxlwtxlutils在excel里面如何插入一行数据

python xlwt,xlutils 在excel里面如何插入一行数据 import xlwt;import xlrd;from xlutils.copy import copy; #styleBoldRed = xlwt.easyxf('font: color-index red, bold on');#headerStyle = styleBoldRed;#wb = xlwt.Workbook();#ws = wb.add_sheet('sheetName');#ws.write(0, 0, 'Col1', headerStyle);#ws.write(0, 1, 'Col2', headerStyle);#ws.write(0, 2, 'Col3', headerStyle);#wb.save('fileName.xls');#open existed xls fileoldWb = xlrd.open_workbook('fileName.xls', formatting_info=True);oldWbS = oldWb.sheet_by_index(0)newWb = copy(oldWb);newWs = newWb.get_sheet(0);inserRowNo = 1newWs.write(inserRowNo, 0, 'value1');newWs.write(inserRowNo, 1, 'value2');newWs.write(inserRowNo, 2, 'value3');for rowIndex in range(inserRowNo, oldWbS.nrows): for colIndex in range(oldWbS.ncols): newWs.write(rowIndex + 1, colIndex, oldWbS.cell(rowIndex, colIndex).value);newWb.save('fileName.xls');print 'save

Python对Excel操作详解

Python对Excel操作 详解 文档摘要: 本文档主要介绍如何通过python对office excel进行读写操作,使用了xlrd、xlwt 和xlutils模块。另外还演示了如何通过Tcl tcom包对excel操作。 关键字: Python、Excel、xlrd、xlwt、xlutils、TCl、tcom

1Python简介 Python是一种面向对象、直译式电脑编程语言,具有近二十年的发展历史,成熟且稳定。它包含了一组完善而且容易理解的标准库,能够轻松完成很多常见的任务。它的语法简捷和清晰,尽量使用无异义的英语单词,与其它大多数程序设计语言使用大括号不一样,它使用縮进来定义语句块。 与Scheme、Ruby、Perl、Tcl等动态语言一样,Python具备垃圾回收功能,能够自动管理存储器使用。它经常被当作脚本语言用于处理系统管理任务和网络程序编写,然而它也非常适合完成各种高级任务。Python虚拟机本身几乎可以在所有的作业系统中运行。使用一些诸如py2exe、PyPy、PyInstaller之类的工具可以将Python源代码转换成可以脱离Python解释器运行的程序。 2Python安装 Python目前的版本已经更新到3.4.0,本文使用的版本为2.7.5,所有的版本都可以在python官网https://www.360docs.net/doc/f76074760.html,/下载,至于2.x和3.x版本的具体区别也可以在官网查看。 从官网下载了python 2.7.5安装文件python-2.7.5.msi后,直接双击就可以安装python了,可以选择安装路径,我改为C:\Python2.7.5\了,然后一路next就完成安装了,安装完成后在C盘下就多了一个文件夹Python2.7.5。 Python也是一种实时交互语言,可以通过自带的IDLE编写python语句并反馈回显信息,可以通过图1方式调出python IDLE。 图1

(整理)python操作excel.

You are here: Home?计算机?编程? Python操作Excel Python操作Excel 2012-09-01 老婆单位有时候有一些很大的 Excel 统计报表需要处理,其中最恶心的是跨表的 JOIN 查询。他们通常采取的做法是,把多个 Excel 工作簿合成一个工作簿的多个表格,然后再跑函数(VLOOKUP之类)去查。因为用的函数效率很低,在 CPU 打满的情况下还要跑几个小时。 然后我就看不过去了,我也不懂 Excel,不知道如何优化,但我想用Python+SQLite 总归是能够实现的。于是就尝试了一把,效果还不错,一分钟以内完成统计很轻松,其中大部分时间主要花在读 Excel 内容上。 1. Python 操作 Excel 的函数库 我主要尝试了 3 种读写 Excel 的方法: 1> xlrd, xlwt, xlutils: 这三个库的好处是不需要其它支持,在任何操作系统上都可以使用。xlrd 可以读取 .xls, .xlsx 文件,非常好用;但因为 xlwt 不能直接修改 Excel 文档,必须得复制一份然后另存为其它文件,而且据说写复杂格式的 Excel 文件会出现问题,所以我没有选它来写 Excel 文件。 2> openpyxl: 这个库也是不需要其它支持的,而且据说对 Office 2007 格式支持得更好。遗憾地是,我经过测试,发现它加载 Excel 文件的效率比 xlrd 慢 3 倍以上,内存使用在 10 倍以上,于是就放弃了。 3> win32com: Python Win32 扩展,这个库需要运行环境为 Windows+Office 对应版本。由于 Python Win32 扩展只是把 COM 接口包装了一下,可以视为与VBA 完全相同,不会有读写格式上的问题。尝试了一下用 win32com 读取 Excel 文件,效率还是比 xlrd 慢一些。 由于读取效率上 xlrd > win32com > openpyxl,所以我自然选择了 xlrd 用来读取统计报表;而最终输出的报表格式较复杂,所以选择了 win32com 直接操作 Excel 文件。 2. Python 里的关系型数据库 SQLite是一个非常轻量级的关系型数据库,很多语言和平台都内置 SQLite 支持,也是 iOS 和 Android 上的默认数据库。Python 的标准库里也包含了sqlite3库,用起来非常方便。

九、Python (openpyxl)操作excel写支持xlsx格式(二)

pip install openpyxl(写,支持xlsx格式) 新建文件 #1.新建一个Excel wb=workbook.Workbook() #2.创建表单的方法 创建一个自定义的表单 wb.create_sheet('info',index=0) #3.另存为 保存工作簿 wb.save('D:\excel\pythonexcel.xlsx') 打开文件写入 #1.打开的工作簿 wb=load_workbook(filename) #2.定位到表单 sheet=wb['info'] #3.cell(I行,J列),必须从1开始 sheet.cell(1,1).value='姓名' #4.保存工作簿 wb.save('D:\excel\pythonexcel.xlsx') 源码 #!/usr/bin/python3 # encoding:utf‐8 import os from openpyxl import workbook from openpyxl import load_workbook ''' 支持xlsx格式写 ''' class excel(): def wirteExcle(self,filename,data): #新建一个Excel wb=workbook.Workbook() #创建表单的方法 创建一个自定义的表单 wb.create_sheet('info',index=0) #另存为 保存工作簿

wb.save(filename) #打开的工作簿 wb=load_workbook(filename) #定位到表单 sheet=wb['info'] c=1 for students in data: #3.标题cell(i行,j列),必须1开始 sheet.cell(1,1).value='姓名' sheet.cell(1,2).value='年龄' #内容(行,列,值)第一行=0,第一列=0 sheet.cell(c,1).value=students['name'] sheet.cell(c,2).value=students['age'] c+=1 #将工作簿以filename命名并保存 wb.save(filename) #5.关闭文件 wb.close() if __name__=='__main__': str= [{'name':'zhangshan','age':19}, {'name':'lisi','age':28}, {'name':'wangwu','age':59}] exl = excel() exl.wirteExcle('D:\excel\pythonexcel.xlsx',str) 打印execel内容

Python对Excel操作教程

Python 对Excel 操作详解文档摘要: 本文档主要介绍如何通过python 对office excel 进行读写操作,使用了xlrd 、xlwt 和xlutils 模块。另外还演示了如何通过Tcl tcom 包对excel 操作。 关键字: Python、Excel、xlrd 、xlwt 、xlutils、TCl 、tcom 1 Python 简介 Python 是一种面向对象、直译式电脑编程语言,具有近二十年的发展历史,成熟且稳定。它包含了一组完善而且容易理解的标准库,能够轻松完成很多常见的任务。它的语法简捷和清晰,尽量使用无异义的英语单词,与其它大多数程序设计语言使用大括号不一样,它使用缩进来定义语句块。 与Scheme、Ruby、Perl 、Tcl 等动态语言一样,Python 具备垃圾回收功能,能够自动管理存储器使用。它经常被当作脚本语言用于处理系统管理任务和网络程序编写,然而它也非常适合完成各种高级任务。Python 虚拟机本身几乎可以在所有的作业系统中运行。使用一些诸如py2exe、PyPy、PyInstaller 之类的工具可以将Python 源代码转换成可以脱离Python 解释器运行的程序。 2 Python 安装 Python 目前的版本已经更新到3.4.0 ,本文使用的版本为2.7.5 ,所有的版本都可以在python 官网下载,至于 2.x 和 3.x 版本的具体区别也可以在官网查看。 从官网下载了python 2.7.5 安装文件后,直接双击就可以安装python

Python 也是一种实时交互语言,可以通过自带的IDLE 编写python 语句并反馈回显信息,可以通过图 1 方式调出python IDLE 。 图1 也可以在cmd下输入python ,但默认情况下python并没有添加到windows 环境变量中,导致在cmd下输入python的时候出现提示“ 'python'不是内部或外部命令,也不是可运行的程序或批处理文件。”,windows 下可执行文件在运行时首先在当前目录下搜索,因为进入cmd 下默认路径一般为C:\Documents and Settings\Administrator> ,而在这个路径下是找不到python 的,所以提示出错,可以进入到python 安装目录下,然后执行python 就可以进入交互命令行模式下。如果懒的每次都进入python 安装,此时需要将python 安装路径添加到系统变量中,然后windows 在执行命令的时候会去环境变量中查找路径,具体配置如图 2 所示,在Path 中添加python 的安装路径 “C:\Python2.7.5; ”,主要路径后面要加”;”分号表面这是一个路径的结束,此时无论在哪个路径下都可以执行python 调出交互命令行。 图2 3 Python 语法入门 在Python 简介中提到Python 是一种直译式电脑编程语言,体现在语法中,如要将变量 a 赋值为1,Tcl 使用命令%set a 1(本文中为了区分Tcl 和Python 的命令,Tcl 命令前会加上“ %”,否则默认为Python 命令),在python 中命令为a = 1,输出a的值可以直接输入a,也可以通过print语句输出a的值, 命令为print a (在python 3.0 以后版本中,print 不再是一个语句,而是一个函数,所以如果想要输出a,用法为print(a))。在Tel中求1和10的和或者变量之间

python学习笔记-excel用例输入

python学习笔记(接口自动化框架V2.0) 这个是根据上次框架版本进行的优化 用python获取excel文件中测试用例数据 通过requets测试接口、并使用正则表达式验证响应信息内容生成xml文件测试报告 版本更新内容: 1. 整理了CreateTest.test_main()流程逻辑 2. 优化了testcase.xls文件格式 3. 添加了生成XML文件测试报告 代码如下: 1#!/usr/bin/env python 2# -*- coding: utf_8 -*- 3# 获取测试用例文件excel 4 5import xlrd 6import json 7 8 9class CreateExcel: 10def__init__(self): 11pass 12 13 @classmethod 14def open_excel(cls):

15 path = "testcase.xls" 16 workbook = xlrd.open_workbook(path) 17 table = workbook.sheets()[0] 18return table 19 20# 获取sheet 21 22 @classmethod 23def get_nrows(cls, table): 24 nrows = table.nrows 25return nrows 26 27# 获取行号 28 29 @classmethod 30def get_id(cls, table, nrows): 31 testid = [] 32for i in range(1, nrows): 33 testid.append(table.cell(i, 0).value) 34return testid 35 36 @classmethod 37def get_name(cls, table, nrows): 38 testname = [] 39for i in range(1, nrows): 40 testname.append(table.cell(i, 1).value) 41return testname 42 43# 获取用例name 44 45 @classmethod 46def get_data(cls, table, nrows): 47 testdata = [] 48for i in range(1, nrows): 49try: 50 data = json.loads(table.cell(i, 2).value) 51 testdata.append(data) 52except ValueError: 53 testdata.append(None) 54return testdata 55 56# 获取data接口参数 57 58 @classmethod 59def get_url(cls, table, nrows): 60 testurl = [] 61for i in range(1, nrows): 62 testurl.append(table.cell(i, 3).value) 63return testurl 64

python复制和编辑excel

#coding=utf-8 import os import os.path import sys from xlrd import open_workbook from xlutils.copy import copy from g315.config import conf import chardet import re p=https://www.360docs.net/doc/f76074760.html,pile(r'(?i){{(.*?)}}') source_file_mold = os.path.join(conf.APP_DIR, "public/excel/source/module.xls") target_file_mold = os.path.join(conf.APP_DIR, "public/excel/target/result.xls") import xlrd import xlwt from xlrd import open_workbook,cellnameabs from xlutils.copy import copy def copy_xf(rdbook,rdxf): """ clone a XFstyle from xlrd XF class,the code is copied from xlutils.copy module """ wtxf = xlwt.Style.XFStyle() # # number format # wtxf.num_format_str = rdbook.format_map[rdxf.format_key].format_str # # font # wtf = wtxf.font rdf = rdbook.font_list[rdxf.font_index] wtf.height = rdf.height wtf.italic = rdf.italic wtf.struck_out = rdf.struck_out wtf.outline = rdf.outline wtf.shadow = rdf.outline wtf.colour_index = rdf.colour_index wtf.bold = rdf.bold #### This attribute is redundant, should be driven by weight wtf._weight = rdf.weight #### Why "private"? wtf.escapement = rdf.escapement

九、Python 操作excel(一)

pip install xlrd(读) 1.导入:import xlrd 2.打开文件:book = xlrd.open_workbook(文件位置+文件名) 3.根据sheet名称获取工作薄:sheet = book.sheet_by_name('Sheet5') 4.获取行数:rows = sheet.nrows 5.获取列数:cols = sheet.ncols 6. 按行获取值:for r in range(rows): row_vaule = sheet.row_values(r) 7.按列获取值: for c in range(cols): col_vuale = sheet.col_values(c) 8.按行列获取值:sheet.cell(行,列) 注:行列第一行下标从0开始 pip install xlwt(写,不支持xlsx格式) 1.导入:import xlwt 2.初始化并创建一个工作簿:book = xlwt.Workbook() 3.sheet = book.add_sheet('Sheet5',cell_overwrite_ok = True) #同一个单元格重复写入数据设 置,book.add_sheet('Sheet5',cell_overwrite_ok = True) 4.按行列写入:sheet.write(行,列,'内容') 5.合并信息并写入样式:sheet.write_merge(开始行,结束行,开始列,结束列,'内 容',self.styleExcle(2,3)) #self.styleExcle(2,3)自定义函数,2,3为参数,详见下面的实例 6.保存:book.save(文件位置+文件名) pip install xlutils(结合读写可修改excel) 1.导入:from xlutils.copy import copy import os 2.打开文件:book = xlrd.open_workbook(filename) 3.复制excel:newbook = copy(book) 4.打开第一个工作薄:sheet = newbook.get_sheet(0) 5.修改第2行,第一列的值:sheet.write(1,0,'xiugren') 6.保存文件:newbook.save(copefilename) 7.删除旧文件:os.remove(filename) 8.重命名新文件名为旧文件名:os.rename(copefilename,filename) 文件路径

python 修改Excel文件

用python 的xlwings包,实现每个人的日报合并功能,代码如下: #coding:utf-8 import xlwings as xw import os def get_name(wb): """ 获取所有sheet name :param wb: :return:dict """ temp_dict = {} for shname in wb.sheets: if https://www.360docs.net/doc/f76074760.html,!='': temp_dict[https://www.360docs.net/doc/f76074760.html,] = shname return temp_dict def up_info(info_dict): """ 实现日志的合并 :param info_dict: :return: """ for shname in info_dict: f_name = '%s.xls'%shname if os.path.exists(f_name): wb = xw.Book(f_name) dt_info = get_name(wb) if shname in dt_info: info_dict[shname].range('A2:D2').expand('down').value = dt_info[shname].range('A2:D2').expand('down').value #print len(dt_info[shname].range('A2:D2').expand('down').value) wb.close() if __name__=='__main__': hzwb = xw.Book(u'日报汇总.xls') name_dict = get_name(hzwb) up_info(name_dict) hzwb.save(u'日报汇总.xls') hzwb.close()

Python对Ecel操作教程

Python对Excel操作详解 文档摘要: 本文档主要介绍如何通过python对office excel进行读写操作,使用了xlrd、xlwt和xlutils模块。另外还演示了如何通过Tcl tcom 包对excel操作。 关键字: Python、Excel、xlrd、xlwt、xlutils、TCl、tcom 1Python简介 Python是一种面向对象、直译式电脑编程语言,具有近二十年的发展历史,成熟且稳定。它包含了一组完善而且容易理解的标准库,能够轻松完成很多常见的任务。它的语法简捷和清晰,尽量使用无异

义的英语单词,与其它大多数程序设计语言使用大括号不一样,它使用縮进来定义语句块。 与Scheme、Ruby、Perl、Tcl等动态语言一样,Python具备垃圾回收功能,能够自动管理存储器使用。它经常被当作脚本语言用于处理系统管理任务和网络程序编写,然而它也非常适合完成各种高级任务。Python虚拟机本身几乎可以在所有的作业系统中运行。使用一些诸如py2exe、PyPy、PyInstaller之类的工具可以将Python源代码转换成可以脱离Python解释器运行的程序。 2Python安装 Python目前的版本已经更新到3.4.0,本文使用的版本为2.7.5,所有的版本都可以在python官网https://www.360docs.net/doc/f76074760.html,/下载,至于2.x和3.x版本的具体区别也可以在官网查看。 从官网下载了python 2.7.5安装文件python-2.7.5.msi后,直接双击就可以安装python了,可以选择安装路径,我改为C:\Python2.7.5\了,然后一路next就完成安装了,安装完成后在C 盘下就多了一个文件夹Python2.7.5。 Python也是一种实时交互语言,可以通过自带的IDLE编写python 语句并反馈回显信息,可以通过图1方式调出python IDLE。

python-excel

Working with Excel files in Python Chris Withers with help from John Machin EuroPython 2009, Birmingham The Tutorial Materials These can be obtained by CD, USB drive or downloaded from here: ?https://www.360docs.net/doc/f76074760.html,/presentations/europython2009excel.zip The Website The best place to start when working with Excel files in Python is the website:?https://www.360docs.net/doc/f76074760.html, ? Simplistix Ltd 2009

License THE WORK (AS DEFINED BELOW) IS PROVIDED UNDER THE TERMS OF THIS CREATIVE COMMONS PUBLIC LICENCE ("CCPL" OR "LICENCE"). THE WORK IS PROTECTED BY COPYRIGHT AND/OR OTHER APPLICABLE LAW. ANY USE OF THE WORK OTHER THAN AS AUTHORIZED UNDER THIS LICENCE OR COPYRIGHT LAW IS PROHIBITED. BY EXERCISING ANY RIGHTS TO THE WORK PROVIDED HERE, YOU ACCEPT AND AGREE TO BE BOUND BY THE TERMS OF THIS LICENCE. THE LICENSOR GRANTS YOU THE RIGHTS CONTAINED HERE IN CONSIDERATION OF YOUR ACCEPTANCE OF SUCH TERMS AND CONDITIONS. This Creative Commons England and Wales Public Licence enables You (all capitalised terms defined below) to view, edit, modify, translate and distribute Works worldwide for Non-Commercial purposes under the terms of this Licence, provided that You credit the Original Author. 'The Licensor' [one or more legally recognised persons or entities offering the Work under the terms and conditions of this Licence] and 'You' agree as follows: 1. Definitions a)"Attribution" means acknowledging all the parties who have contributed to and have rights in the Work or Collective Work under this Licence. b)"Collective Work" means the Work in its entirety in unmodified form along with a number of other separate and independent works, assembled into a collective whole. c)"Derivative Work" means any work created by the editing, modification, adaptation or translation of the Work in any media (however a work that constitutes a Collective Work will not be considered a Derivative Work for the purpose of this Licence). For the avoidance of doubt, where the Work is a musical composition or sound recording, the synchronization of the Work in timed-relation with a moving image ("synching") will be considered a Derivative Work for the purpose of this Licence. d)"Licence" means this Creative Commons England and Wales Public Licence agreement. e)"Non-Commercial" means "not primarily intended for or directed towards commercial advantage or private monetary compensation". The exchange of the Work for other copyrighted works by means of digital file-sharing or otherwise shall not be considered to be intended for or directed towards commercial advantage or private monetary compensation, provided there is no payment of any monetary compensation in connection with the exchange of copyrighted works. f)"Original Author" means the individual (or entity) who created the Work. g)"Work" means the work protected by copyright which is offered under the terms of this Licence. h)For the purpose of this Licence, when not inconsistent with the context, words in the singular number include the plural number. 2. Licence Terms 2.1 The Licensor hereby grants to You a worldwide, royalty-free, non-exclusive, Licence for Non-Commercial use and for the duration of copyright in the Work. You may: ?copy the Work; ?incorporate the Work into one or more Collective Works; ?copy the Work as incorporated in any Collective Work; and ?publish, distribute, archive, perform or otherwise disseminate the Work or the Work as incorporated in any Collective Work, to the public in any material form in any media whether now known or hereafter created. HOWEVER, You must not: ?impose any terms on the use to be made of the Work, the Work as incorporated in a Collective Work that alter or restrict the terms of this Licence or any rights granted under it or has the effect or intent of restricting the ability to exercise those rights; ?impose any digital rights management technology on the Work, the Work as incorporated in a Collective Work that alters or restricts the terms of this Licence or any rights granted under it or has the effect or intent of restricting the ability to exercise those rights; ?make any Derivative Works; ?sublicense the Work; ?subject the Work to any derogatory treatment as defined in the Copyright, Designs and Patents Act 1988. FINALLY, You must: ?make reference to this Licence (by Uniform Resource Identifier (URI), spoken word or as appropriate to the media used) on all copies of the Work and Collective Works published, distributed, performed or otherwise disseminated or made available to the public by You; ?recognise the Licensor's / Original Author's right of attribution in any Work and Collective Work that You publish, distribute, perform or otherwise disseminate to the public and ensure that You credit the Licensor / Original Author as appropriate to the media used; and ?to the extent reasonably practicable, keep intact all notices that refer to this Licence, in particular the URI, if any, that the Licensor specifies to be associated with the Work, unless such URI does not refer to the copyright notice or licensing information for the Work. Additional Provisions for third parties making use of the Work 2.2. Further licence from the Licensor Each time You publish, distribute, perform or otherwise disseminate ?the Work; or ?the Work as incorporated in a Collective Work the Licensor agrees to offer to the relevant third party making use of the Work (in any of the alternatives set out above) a licence to use the Work on the same terms and conditions as granted to You hereunder. 2.3. This Licence does not affect any rights that the User may have under any applicable law, including fair use, fair dealing or any other legally recognised limitation or exception to copyright infringement.

相关文档
最新文档