python复制和编辑excel

python复制和编辑excel
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/519335788.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

wtf.underline = rdf.underline_type ####

# wtf.???? = rdf.underline #### redundant attribute, set on the fly when writing wtf.family = rdf.family

wtf.charset = rdf.character_set

https://www.360docs.net/doc/519335788.html, = https://www.360docs.net/doc/519335788.html,

#

# protection

#

wtp = wtxf.protection

rdp = rdxf.protection

wtp.cell_locked = rdp.cell_locked

wtp.formula_hidden = rdp.formula_hidden

#

# border(s) (rename ????)

#

wtb = wtxf.borders

rdb = rdxf.border

wtb.left = rdb.left_line_style

wtb.right = rdb.right_line_style

wtb.top = rdb.top_line_style

wtb.bottom = rdb.bottom_line_style

wtb.diag = rdb.diag_line_style

wtb.left_colour = rdb.left_colour_index

wtb.right_colour = rdb.right_colour_index

wtb.top_colour = rdb.top_colour_index

wtb.bottom_colour = rdb.bottom_colour_index

wtb.diag_colour = rdb.diag_colour_index

wtb.need_diag1 = rdb.diag_down

wtb.need_diag2 = rdb.diag_up

#

# background / pattern (rename???)

#

wtpat = wtxf.pattern

rdbg = rdxf.background

wtpat.pattern = rdbg.fill_pattern

wtpat.pattern_fore_colour = rdbg.pattern_colour_index

wtpat.pattern_back_colour = rdbg.background_colour_index

#

# alignment

#

wta = wtxf.alignment

rda = rdxf.alignment

wta.horz = rda.hor_align

wta.vert = rda.vert_align

wta.dire = rda.text_direction

# wta.orie # orientation doesn't occur in BIFF8! Superceded by rotation ("rota").

wta.rota = rda.rotation

wta.wrap = rda.text_wrapped

wta.shri = rda.shrink_to_fit

wta.inde = rda.indent_level

# wta.merg = ????

#

return wtxf

def fill_value(position_sheet={},cell_value=""):

"""

replace the position({{varible}}) of the cellvalue with the varible's value

"""

if cell_value:

m=p.search(cell_value)#查询是否存在{{?p}}

while m:

var_name=m.groups()[0]

print "var_name:",var_name

try:

value = position_sheet.get(var_name) #读取第一个参数的值

except Exception, e:

error= u"模板文件:%(source_file)s的第%(index)s个sheet中的参数{{%(var_name)s}}在position中找不到对应的key" % \

{"source_file":os.path.split(source_file)[1],"index":i+1,"var_name":var_name}

print error

return dict(error=error,e=e)

if value and not isinstance(value, unicode):

value= value.decode("utf-8")

print 'value', value

if not value:

break

cell_value=p.sub(value,cell_value,count=1)#用这个值替换cell_value中的该{{参数}}

m=p.search(cell_value)#检查是否还有参数

return cell_value

def excel_create(source_file="",position=[{}],target_file=""):

'''

根据source_file传入的excel模板文件路径,使用position中map对模板中的{{varible}}中的varible字段进行数据填充,生成新的文件放入file_path

source_file:模板文件名;非空路径为:/public/excel/source/.xls,空值默认模板:/public/excel/source/module.xls,

position:[{key:value,key1:value1,key2:value2,...},#模板excel的sheet[0]内的参数map {key:value,key1:value1,key2:value2,...},#模板excel的sheet[1]内的参数map

{key:value,key1:value1,key2:value2,...},#模板excel的sheet[...]内的参数map

]

file_path:生成的文件路径以及文件名;空值为默认路径:public/excel/target/result.xls '''

warning=""

if target_file:

result_file=os.path.join(conf.APP_DIR, "public/excel/target", target_file) else:

result_file=target_file_mold

if source_file:

source_file=os.path.join(conf.APP_DIR, "public/excel/source", source_file) else:

source_file=source_file_mold

try:

rb = open_workbook(source_file,on_demand=True,formatting_info=True) except:

error= u"the (%s) is not a correct path!" % source_file

return dict(error=error)

wb = copy(rb)

shxrange = range(rb.nsheets)

while len(shxrange)>len(position):

warning= u"the length of position's map is lesser than the number of the module Excel's sheets!"

position.append({})

for i in shxrange:

ws = wb.get_sheet(i)

sheet = rb.sheet_by_index(i)

for rowx in range(0,sheet.nrows):

for colx in range(0,sheet.ncols):

#get the cell value

cellvalue=sheet.cell_value(rowx,colx)

#get the cell type

celltype=sheet.cell_type(rowx,colx)

if celltype == xlrd.XL_CELL_DATE:

try:

showval = xlrd.xldate_as_tuple(cellvalue, rb.datemode)

except xlrd.XLDateError:

e1, e2 = sys.exc_info()[:2]

showval = "%s:%s" % (e1.__name__, e2)

elif celltype == xlrd.XL_CELL_ERROR:

showval = xlrd.error_text_from_code.get(

cellvalue, 'Unknown error code 0x%02x' % cellvalue)

else:

showval = cellvalue

#get style

xf=rb.xf_list[sheet.cell_xf_index(rowx,colx)]

wtxf=copy_xf(rb,xf)

#fill value(replace the varible in the cell_value)

if showval:

m=p.search(showval)#查询是否存在{{?p}}

while m:

var_name=m.groups()[0]

try:

if var_name in position[i].keys():

value = position[i].get(var_name,"") #读取第一个参数的值

print "begin||",var_name,":",value,chardet.detect(value)

# assert value is True

if value:

if not isinstance(value, unicode):

value= value.decode("utf-8")

else:

value=""

print "decode||",var_name,":",value

print "-----------------------------------"

else:

raise Exception

except Exception, e:

error= u"the param:{{%(var_name)s}} in sheet(%(index)s) of the template:%(source_file)s can't be found in position's keys list" % \

{"source_file":os.path.split(source_file)[1],"index":i+1,"var_name":var_name}

print error,e

return dict(error=error.encode('utf-8'))

showval=p.sub(value,showval,count=1)#用这个值替换cell_value 中的该{{参数}}

m=p.search(showval)#检查是否还有参数

ws.write(rowx,colx,showval,wtxf)

wb.save(result_file)

return dict(target_file=os.path.join("/public/excel/target",target_file),warning=warning)

def _test():

#open the excel file

rb=open_workbook("test1.xls",on_demand=True,formatting_info=True)

for attr in ("biff_version","codepage","countries","encoding",

"colour_map","font_list","format_list","format_map",

"user_name",

"nsheets"):

print "%s=%s" %(attr, rb.__getattribute__(attr))

#show the loaded status for sheets

for sheet_name in rb.sheet_names():

print "%s loaded = %s" %(sheet_name, rb.sheet_loaded(sheet_name))

#get the sheet1

sheet=rb.sheet_by_index(0)

print "%s has %d rows, %d cols" %(https://www.360docs.net/doc/519335788.html,, sheet.nrows, sheet.ncols)

print "Shoe the file content"

for rowx in range(0,sheet.nrows):

for colx in range(0,sheet.ncols):

#get the cell value

cellvalue=sheet.cell_value(rowx,colx)

#get the cell type

celltype=sheet.cell_type(rowx,colx)

#init the showable value

showvalue=""

if celltype == xlrd.XL_CELL_DATE:

try:

showval = xlrd.xldate_as_tuple(cellvalue, rb.datemode)

except xlrd.XLDateError:

e1, e2 = sys.exc_info()[:2]

showval = "%s:%s" % (e1.__name__, e2)

elif celltype == xlrd.XL_CELL_ERROR:

showval = xlrd.error_text_from_code.get(

cellvalue, 'Unknown error code 0x%02x' % cellvalue)

else:

showval = cellvalue

#get style

xf=rb.xf_list[sheet.cell_xf_index(rowx,colx)]

#print rb.colour_map[xf.background.background_colour_index]

#display the cell forecolor

color=rb.colour_map[xf.background.pattern_colour_index]

#show the content

print ("[%s]=%s,[color]=%s" % (cellnameabs(rowx,colx),showval,color))

#show the loaded status for sheets after load sheet1

for sheet_name in rb.sheet_names():

print "%s loaded = %s" %(sheet_name, rb.sheet_loaded(sheet_name))

#################

#change the excel and write it out

#################

#get the xlwt object from rb object

wb = copy(rb)

#get the original excel cell style

rbxf=rb.xf_list[sheet.cell_xf_index(0,0)]

#copy the xlrd style to xlwt style

wtrf=copyXF(rb,rbxf)

#change an attribute of this style, the color index can refer to VBA document wtrf.pattern.pattern_fore_colour=15

#set the new value and new style

#wb.get_sheet(0).write(0,0,'changed!')

wb.get_sheet(0).write(0,0,'changed!',wtrf)

#output to file

wb.save('test2.xls')

def test(source_file="",position=[{}],target_file=""):

'''

根据source_file传入的excel模板文件路径,使用position中map对模板中的{{varible}}中的varible字段进行数据填充,生成新的文件放入file_path

source_file:模板文件名;非空路径为:/public/excel/source/.xls,空值默认模板:/public/excel/source/module.xls,

position:[{key:value,key1:value1,key2:value2,...},#模板excel的sheet[0]内的参数map {key:value,key1:value1,key2:value2,...},#模板excel的sheet[1]内的参数map

{key:value,key1:value1,key2:value2,...},#模板excel的sheet[...]内的参数map

]

file_path:生成的文件路径以及文件名;空值为默认路径:public/excel/target/result.xls '''

print position

if target_file:

target_file=os.path.join(conf.APP_DIR, "public/excel/target", target_file) else:

target_file=target_file_mold

if source_file:

source_file=os.path.join(conf.APP_DIR, "public/excel/source", source_file) else:

source_file=source_file_mold

try:

rb = open_workbook(source_file,formatting_info=True)

except:

print "(%s)路径名不正确" % source_file

error= "(%s)路径名不正确" % source_file

return dict(error=error)

wb = copy(rb)

shxrange = range(rb.nsheets)

while len(shxrange)>len(position):

print '警告:position的map数小于sheets个数'

position.append({})

for index in shxrange:

ws = wb.get_sheet(index)

sh = rb.sheet_by_index(index)

nrows = sh.nrows

ncols = sh.ncols

for i in range(0,nrows):

for j in range(0,ncols):

cell_value=sh.cell(i,j).value

cell_type=sh.cell(i,j).type

m=p.search(cell_value)#查询是否存在{{?p}}

while m:

var_name=m.groups()[0]

print "var_name:",var_name

try:

value = position[index].get(var_name) #读取第一个参数的值

if value and not isinstance(value, unicode):

value= value.decode("utf-8")

except Exception, e:

error= u"模板文件:%(source_file)s的第%(index)s个sheet中的参数{{%(var_name)s}}在position中找不到对应的key" % \

{"source_file":os.path.split(source_file)[1],"index":index+1,"var_name":var_name}

print error

return dict(error=error)

print 'value', value

if not value:

break

cell_value=p.sub(value,cell_value,count=1)#用这个值替换cell_value中的该{{参数}}

m=p.search(cell_value)#检查是否还有参数

#把处理后的cell_value填入结果单元格

try:

ws.write(i, j, cell_value)

except:

error= u"excel写入失败"

return dict(error=error)

wb.save(target_file)

return dict(target_file=target_file)

def test2():

pass

# Step 1: Create an input file for the demo

def create_input_file():

wtbook = xlwt.Workbook()

wtsheet = wtbook.add_sheet(u'First')

colours = 'white black red green blue pink turquoise yellow'.split()

fancy_styles = [xlwt.easyxf(

'font: name Times New Roman, italic on;'

'pattern: pattern solid, fore_colour %s;'

% colour) for colour in colours]

for rowx in xrange(8):

wtsheet.write(rowx, 0, rowx)

wtsheet.write(rowx, 1, colours[rowx], fancy_styles[rowx]) wtbook.save('demo_copy2_in.xls')

# Step 2: Copy the file, changing data content

# ('pink' -> 'MAGENTA', 'turquoise' -> 'CYAN')

# without changing the formatting

from xlutils.filter import process,XLRDReader,XLWTWriter

# Patch: add this function to the end of xlutils/copy.py

def copy2(wb):

w = XLWTWriter()

process(

XLRDReader(wb,'unknown.xls'),

w

)

return w.output[0][1], w.style_list

def update_content():

rdbook = xlrd.open_workbook('demo_copy2_in.xls', formatting_info=True) sheetx = 0

rdsheet = rdbook.sheet_by_index(sheetx)

wtbook, style_list = copy2(rdbook)

wtsheet = wtbook.get_sheet(sheetx)

fixups = [(5, 1, 'MAGENTA'), (6, 1, 'CYAN')]

for rowx, colx, value in fixups:

xf_index = rdsheet.cell_xf_index(rowx, colx)

wtsheet.write(rowx, colx, value, style_list[xf_index])

wtbook.save('demo_copy2_out.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/519335788.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/519335788.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/519335788.html,!='': temp_dict[https://www.360docs.net/doc/519335788.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/519335788.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/519335788.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/519335788.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.

相关文档
最新文档