2、打开Excel文件读取数据
data = xlrd.open_workbook('excelFile.xls')[1]
3、使用技巧
获取一个工作表
table = data.sheets()[0] #通过索引顺序获取
table = data.sheet_by_index(0) #通过索引顺序获取
table = data.sheet_by_name(u'Sheet1')#通过名称获取
获取整行和整列的值(数组)
table.row_values(i)
table.col_values(i)
获取行数和列数
nrows = table.nrows
ncols = table.ncols
循环行列表数据
for i in range(nrows ):
print table.row_values(i)
单元格
table.cell(rowx,colx)
cell_A1 = table.cell(0,0).value
cell_C4 = table.cell(3,2).value
使用行列索引
cell_A1 = table.row(0)[0].value
cell_A2 = table.col(1)[0].value
简单的写入
row = 0
col = 0
# 类型 0 empty,1 string, 2 number, 3 date, 4 boolean, 5 error
ctype = 1value = '单元格的值'
xf = 0# 扩展的格式化
table.put_cell(row, col, ctype, value, xf)
table.cell(0,0) #单元格的值'
table.cell(0,0).value #单元格的值'
xlwt简单用法说明
在写入Excel表格之前,你必须初始化workbook对象,然后添加一个workbook对象。比如:
1 import xlwt
2 wbk = xlwt.Workbook()
3 sheet = wbk.add_sheet('sheet 1')
这样表单就被创建了,写入数据也很简单:
1 # indexing is zero based, row then column
2 sheet.write(0,1,'test text')
之后,就可以保存文件(这里不需要想打开文件一样需要close文件):
1 wbk.save('test.xls')
深入探索
worksheet对象,当你更改表单内容的时候,会有警告提示。
1 sheet.write(0,0,'test')
2 sheet.write(0,0,'oops')
3
4 # returns error:
5 # Exception: Attempt to overwrite cell:
6 # sheetname=u'sheet 1' rowx=0 colx=0
解决方式:使用cell_overwrite_ok=True来创建worksheet:
1 sheet2 = wbk.add_sheet('sheet 2', cell_overwrite_ok=True)
2 sheet2.write(0,0,'some text')
3 sheet2.write(0,0,'this should overwrite')
这样你就可以更改表单2的内容了。
更多
1 # Initialize a style
2 style. = xlwt.XFStyle()
3
4 # Create a font to use with the style
5 font = xlwt.Font()
6 font.name = 'Times New Roman'
7 font.bold = True
8
9 # Set the style's font to this new one you set up
10 style.font = font
11
12 # Use the style. when writing
13 sheet.write(0, 0, 'some bold Times text', style)
xlwt 允许你每个格子或者整行地设置格式。还可以允许你添加链接以及公式。其实你可以阅读源代码,那里有很多例子:
dates.py, 展示如何设置不同的数据格式
hyperlinks.py, 展示如何创建超链接 (hint: you need to use a formula)
merged.py, 展示如何合并格子
row_styles.py, 展示如何应用Style到整行格子中.