现在的位置: 首页 > 编程语言 > 正文

python excel 的相关操作

2019年08月05日 编程语言 ⁄ 共 1402字 ⁄ 字号 评论关闭

source:http://www.2cto.com/kf/201208/145583.html

因为经常用到对excel的相关操作,今天就在此总结相关内容,方便大家参考。

python操作excel除了读就是写。

从读开始

xlrd

http://pypi.python.org/pypi/xlrd

导入
import xlrd

打开excel
file = xlrd.open_workbook('demo.xls')

查看文件中包含sheet的名称
file.sheet_names()

得到第一个工作表,或者通过索引顺序 或 工作表名称
sheet = file.sheets()[0]
sheet = file.sheet_by_index(0)
sheet = file.sheet_by_name(u'Sheet1')

获取行数和列数
nrows = sheet.nrows
ncols = sheet.ncols

循环行,得到索引的列表
for rownum in range(sheet.nrows):
    print sheet.row_values(rownum)

获取整行和整列的值(数组)
sheet.row_values(i)
sheet.col_values(i)

单元格(索引获取)
cell_A1 = sheet.cell(0,0).value
cell_C4 = sheet.cell(2,3).value

分别使用行列索引
cell_A1 = sheet.row(0)[0].value
cell_A2 = sheet.col(1)[0].value

 

xlwt

http://pypi.python.org/pypi/xlrd

导入xlwt

import xlwt

新建一个excel文件

file = xlwt.Workbook() #注意这里的Workbook首字母是大写,无语吧

新建一个sheet

sheet = file.add_sheet('sheet name')

写入数据sheet.write(行,列,value)

sheet.write(0,0,'test')

如果对一个单元格重复操作,会引发
returns error:
# Exception: Attempt to overwrite cell:
# sheetname=u'sheet 1' rowx=0 colx=0

所以在打开时加cell_overwrite_ok=True解决

sheet = file.add_sheet('sheet name',cell_overwrite_ok=True)

保存文件

file.save('demo.xls')

另外,使用style

style = xlwt.XFStyle() #初始化样式

font = xlwt.Font() #为样式创建字体

font.name = 'Times New Roman'

font.bold = True

style.font = font #为样式设置字体

sheet.write(0, 0, 'some bold Times text', style) # 使用样式

xlwt 允许单元格或者整行地设置格式。还可以添加链接以及公式。可以阅读源代码,那里有例子:

dates.py, 展示如何设置不同的数据格式www.2cto.com

hyperlinks.py, 展示如何创建超链接 (hint: you need to use a formula)

merged.py, 展示如何合并格子

row_styles.py, 展示如何应用Style到整行格子中.

 作者:寂寞的远行者

抱歉!评论已关闭.