前言
在python中有许多中操作excel的方式,pandas无疑是最好用的,但是在平时写一些小工具时用其他小型包也够了。本篇介绍一下xlutis、xlrd、xlwt的一些基本操作。
正文
xlrd
单元格中的数据类型
empty、string、number、date、boolean、error、blank
常用函数
import xlrd import datetime
data = xlrd.open_workbook('excel.xlsx')
table=data.sheets()[0]
table=data.sheet_by_index(0)
table=data.sheet_by_name('sheet1')
names=data.sheet_names()
data.sheet_loaded(name or index)
table.nrows
table.row(rowx)
table.row_slice(rowx,start_colx,end_colx)
table.row_len(rows)
table.row_types(rows,start_colx,end_colx)
table.row_values(rows,start_colx,end_colx)
table.cell(rowx, colx)
table.cell_value(rowx, colx)
table.cell_type(rowx, colx)
date_tuple=xlrd.xldate_as_tuple(cell_value,data.datemode)
date_value=datetime.date(*date_tuple[:3])
date_value.strftime('%Y%m%d')
table.merged_cells
table.cell_value(rowx_start,col_start)
|
xlutis
xlutis是为了解决xlwt不能向已有数据的excel表格写入数据的局限性。主要使用的是xlutis.copy.copy方法,但是也有弊端,比如表格内的图片等内容不能复制。
file_path = os.path.dirname(os.path.realpath(sys.executable))+'\\'+book book = xlrd.open_workbook(file_path,formatting_info=True)
copy_book = xlutils.copy.copy(book) copy_sheet = copy_book.get_sheet(sheetname)
|
xlwt
xlwt是一个比较简便的操作Excel表格的工具包,处理一些日常表格需求完全足够了。
创建新表格
import xlwt
workbook=xlwt.Workbook() sheet = workbook.add_sheet('sheet', cell_overwrite_ok=True)
sheet.col(0).width = 256 * 15
sheet.row(0).height_mismatch = True sheet.row(0).height = 20 * 40
workbook.save('Excel.xls')
|
设置字体样式
style=xlwt.XFStyle()
font=xlwt.Font()
font.name="Simsun"
font.height=20*11
font.bold=False
font.underline=True
font.italic = True
font.colour_index = 0x01
style.font=font
|
设置单元格样式
- 设置对齐方式
al1=xlwt.Alignment() al1.horz=0x02 al1.vert=0x01 style.alignment=al1 sheet.write(0,0,'al1居中方式',style)
style.alignment.vert=0x01 style.alignment.horz=0x02
VERT_TOP = 0x00 上端对齐 VERT_CENTER = 0x01 居中对齐(垂直方向上) VERT_BOTTOM = 0x02 低端对齐
HORZ_LEFT = 0x01 左端对齐 HORZ_CENTER = 0x02 居中对齐(水平方向上) HORZ_RIGHT = 0x03 右端对齐
|
在单元格设置超链接或公式等内容
sheet.write(0, 0, xlwt.Formula('HYPERLINK("http://www.google.com";"Google")'))
sheet.write(0, 0, xlwt.Formula('HYPERLINK("./test.xls";"test")'))
sheet.write(2, 0, xlwt.Formula('SUM(A1,A2)'))
|
写入日期
style.num_format_str='M/D/YY' sheet.write(2, 0, datetime.datetime.now(),style)
|
设置单元格背景颜色
pattern.pattern = xlwt.Pattern() pattern.pattern=SOLID_PATTERN pattern.pattern_fore_colour=1
style.pattern=pattern
|
设置单元格边框
borders=xlwt.Borders() borders.left=xlwt.Borders.DASHED
borders.left_colour
|
合并单元格
隐藏某列某行
sheet.row(i).hidden =0 显示 =1 隐藏
|
设置页面布局
copy_sheet.portrait = False false 横向 true 纵向
|
去除页眉页脚
copy_sheet.show_headers = False copy_sheet.header_str = b'' copy_sheet.footer_str = b''
|