本文旨在记录对excel 常用操作方式
依赖
包 |
功能 |
xlrd |
读取 |
xlwt |
写入 |
xlutils |
配合xlrd做编辑 |
创建excel
最简单的例子就是创建一个sheet页的文档
1 2 3 4 5
| import xlwt
wb = xlwt.Workbook(encoding='utf-8') sheet = wb.add_sheet("sheet1") wb.save("excel.xls")
|
cell 操作
每个sheet 都是一个二维表,通过 (x,y) 这样的索引对单元格(cell)进行操作
1 2 3 4 5 6 7 8 9 10 11
| sheet.write(0, 1, "string")
sheet.write(0, 2, 1024)
sheet.write(0, 3, True)
selfFormat = xlwt.XFStyle() selfFormat.num_format_str = 'yyyy-mm-dd hh:mm:ss' sheet.write(0, 4, datetime.datetime.now(), selfFormat)
|
在excel中日期、时间是以浮点数存储的,1 = 1900/1/1 0:00:00
,并且每一天+1,时间折算到小数
设置单元格样式
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| font = xlwt.Font() font.name = "Arial" font.bold = True font.color_index = 4
align = xlwt.Alignment() align.horz = xlwt.Alignment.HORZ_CENTER align.vert = xlwt.Alignment.VERT_CENTER
style = xlwt.XFStyle() style.font = font style.alignment = align
sheet.write_merge(0, 3, 0, 0, "合并单元格", style)
|
读取excel
读取需要使用 xlrd ,不能对内容进行修改
1 2 3 4 5 6 7 8 9
| import xlrd
wb = xlrd.open_workbook("excel.xls")
sheet_names = wb.sheet_names() sheet = wb.sheet_by_index(0) sheet = wb.sheet_by_name(u'Sheet1')
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
| sheets = wb.sheets() for sheet in sheets: print("Sheet: %8s Rows: %2s Cols: %2s" % (sheet.name, sheet.nrows, sheet.ncols)) sheet.row_values(0)[:10] sheet.col_values(0)
for i in range(sheet.nrows): for j in range(sheet.ncols): if sheet.cell_type(i, j) == xlrd.XL_CELL_TEXT: print("Type: TEXT Value: %s" % sheet.cell(i, j).value) if sheet.cell_type(i, j) == xlrd.XL_CELL_BOOLEAN: print("Type: BOOLEAN Value: %r" % sheet.cell(i, j).value) if sheet.cell_type(i, j) == xlrd.XL_CELL_NUMBER: print("Type: NUMBER Value: %f" % sheet.cell(i, j).value) if sheet.cell_type(i, j) == xlrd.XL_CELL_DATE: print("Type: DATE Value: %r" % xlrd.xldate.xldate_as_datetime(sheet.cell(i, j).value, 0))
|
编辑excel
需要再加 xlutils 包
1 2 3 4 5 6 7
| import xlrd from xlutils.copy import copy wb = copy(xlrd.open_workbook("excel.xls")) sheet = wb.get_sheet(0) sheet.set_name("copyed_%s" % sheet.get_name()) wb.add_sheet("sheet2") wb.save('new_excel.xls')
|
copy 方法只会拷贝数据,所有样式都会丢失