xlrd/xlwt

Operating excel file xls format

Reading Module

xlrd

import xlrd
open a file

wb= xlrd.open_workbook('xxxx.xls')

Get a table in excel

ws= wb.sheets()[0]       #通过索引顺序获取
ws= wb.sheet_by_index(0) #通过索引顺序获取
ws= wb.sheet_by_name(u'Sheet1')#通过名称获取

Gets the specified row, column values, it returns a list of,

xlrd的索引是从0开始的,
获取第一行的值,索引就是0
ws.row_values(0)  >>[123.0, 123.0, 23.0, 12.0]
获取第一列的值
ws.col_values(0)  >>[1231.0, 123.0, 23.0, 23.0, 23.0, 23.0, 23.0, 23.0]

Gets the number of columns and rows

获取excel的总行数
ws.nrows   >>  7
获取excel总列数
ws.ncols   >>  4

Gets the value of a specified cell

获取第一行第一列的单元格(0,0)对象
ws.cell(0,0)
该单元格对象有value属性,返回单元格的值,为浮点型
ws.cell(0,0).value   >>  123

Write module

xlwt

import xlwd

# 创建wb对象
wb = xlrd.Workbool(encoding='gbk')

# 创建ws对象
ws = wb.add_sheet('sheet名')

# 定义样式
style = xlwt.XFStyle();
headstyle = xlwt.XFStyle();

font = xlwt.Font();
headfont = xlwt.Font();
borders = xlwt.Borders();
lineal = xlwt.Alignment();
headal = xlwt.Alignment();

font.name = 'FangSong';
font.bold = False;        
headfont.name = 'FangSong';
headfont.bold = True;
headfont.height = 220; #20 * 实际字体大小,11号字体为220

borders.left = xlwt.Borders.THIN;
borders.right = xlwt.Borders.THIN;
borders.top = xlwt.Borders.THIN;
borders.bottom = xlwt.Borders.THIN;

headal.horz = 0x02  # 设置水平居中
headal.vert = 0x01  # 设置垂直居中
lineal.vert = 0x01  # 设置垂直居中
lineal.wrap = xlwt.Alignment.WRAP_AT_RIGHT;

style.font = font;
style.borders = borders;
style.alignment = lineal;
headstyle.font = headfont;
headstyle.borders = borders;
headstyle.alignment = headal;

#指定单元格大小
wsheet.col(0).width = 256 * 8;
wsheet.col(1).width = 256 * 30;

#给单元格写入数据
指明行号列号要写的值,注意索引位置是从0开始的
ws.write(0,0,‘测试数据’,style)
指定title的格式
ws.write(0,0,‘测试数据’,headstyle)
#保存文件
wb.save('写xls.xls')

Guess you like

Origin www.cnblogs.com/0916m/p/11484318.html