07-03 xlwt的使用 - 图1


1、基本使用

1.1、创建工作薄

  1. xw = xlwt.Workbook()
  2. # ps:需要注意的点就是通过此方法生成的工作薄,默认的字符编码是ascii,如果有特殊需求,需要自己修改

1.2、添加工作表

  1. cla = xw.add_sheet('test')

1.3、向工作表中写入数据

  1. cla.write(0, 0, 'name')
  2. cla.write(0, 1, 'class')
  3. cla.write(0, 2, 'cid')
  4. cla.write(0, 3, 'gender')

write()方法中的三个参数分别是=(行,列,添加的内容),上面我所添加的就是表头。

1.4、存入本地

  1. xw.save('test.xls')

2、常用函数

接下来所有操作都针对以上工作薄进行

2.1、获取book中的一个工作薄

  1. sheet = xw.add_sheet('x_test', cell_overwrite_ok=False) # 新建一个sheet,默认参数是不允许覆盖

2.2、行的宽度操作

  1. tall_style = xlwt.easyxf("font:height 720;")
  2. sheet.row(0).set_style(tall_style)
  3. # ps:row()方法中括号内填写的是行索引

07-03 xlwt的使用 - 图2

2.3、列(colnum)的宽度操作

  1. sheet.col(0) # 返回列对象,可以针对它做一系列操作
  2. sheet.col(0).get_width() # 获取列的宽度,默认宽度是2962
  3. sheet.col(0).set_style(tall_style) # 设置列的style
  4. sheet.col(0).set_width(2962) # 设置列宽

07-03 xlwt的使用 - 图3

2.4、单元格的操作

  1. sheet.write( r, c, label='', style=<xlwt.Style.XFStyle object>) # 向单元格写入数据