Python xlrd/xlwt 创建excel文件及常用操作


Posted in Python onSeptember 24, 2020

一、创建excel代码

备注:封装好了(可直接调用)

"""
-*- coding:utf-8 -*-
@Time :2020/8/20 21:02
@Author :Jarvis
@File :jar_excel_util.py
@Version:1.0
"""
from typing import List

import xlwt


class JarExcelUtil:
 def __init__(self, header_list: List[list]):
  """
  :param header_list: 如下格式
   例1:默认列宽
   header_list = [
    ['序号'], # 表格第0列[此列表头名称]
    ['姓名'],
    ['性别'],
    ['爱好'],
    ['生日']
   ]
   例2:自定义列宽(列宽值为int类型 英文字符长度 如:10 表示列宽为10个英文字符长度)
   header = [
    ['序号', 5], # 表格第0列[此列表头名称,列宽]
    ['姓名', 10], # 表格第1列[此列表头名称,列宽]
    ['性别', 10],
    ['爱好', 10],
    ['生日', 20]
   ]
  """
  self.data = header_list
  self.__color_str = 'aqua 0x31\r\n\
black 0x08\r\n\
blue 0x0C\r\n\
blue_gray 0x36\r\n\
bright_green 0x0B\r\n\
brown 0x3C\r\n\
coral 0x1D\r\n\
cyan_ega 0x0F\r\n\
dark_blue 0x12\r\n\
dark_blue_ega 0x12\r\n\
dark_green 0x3A\r\n\
dark_green_ega 0x11\r\n\
dark_purple 0x1C\r\n\
dark_red 0x10\r\n\
dark_red_ega 0x10\r\n\
dark_teal 0x38\r\n\
dark_yellow 0x13\r\n\
gold 0x33\r\n\
gray_ega 0x17\r\n\
gray25 0x16\r\n\
gray40 0x37\r\n\
gray50 0x17\r\n\
gray80 0x3F\r\n\
green 0x11\r\n\
ice_blue 0x1F\r\n\
indigo 0x3E\r\n\
ivory 0x1A\r\n\
lavender 0x2E\r\n\
light_blue 0x30\r\n\
light_green 0x2A\r\n\
light_orange 0x34\r\n\
light_turquoise 0x29\r\n\
light_yellow 0x2B\r\n\
lime 0x32\r\n\
magenta_ega 0x0E\r\n\
ocean_blue 0x1E\r\n\
olive_ega 0x13\r\n\
olive_green 0x3B\r\n\
orange 0x35\r\n\
pale_blue 0x2C\r\n\
periwinkle 0x18\r\n\
pink 0x0E\r\n\
plum 0x3D\r\n\
purple_ega 0x14\r\n\
red 0x0A\r\n\
rose 0x2D\r\n\
sea_green 0x39\r\n\
silver_ega 0x16\r\n\
sky_blue 0x28\r\n\
tan 0x2F\r\n\
teal 0x15\r\n\
teal_ega 0x15\r\n\
turquoise 0x0F\r\n\
violet 0x14\r\n\
white 0x09\r\n\
yellow 0x0D'
  self.color_list = [] # [[]] [['aqua', '0x31'], ['black', '0x08'], ...]
  for color in self.__color_str.split('\r\n'):
   color = color.split(' ')
   self.color_list.append(color)

 def write(self, out_file, data_body: List[list], sheet_name='sheet', frozen_row: int = 1, frozen_col: int = 0):
  """
  写入数据
  :param out_file: 保存文件(如:test.xlsx)
  :param data_body: data_body[0]为表格第0行数据 data_body[0][0]为表格第0行第0列单元格值
  :param sheet_name:
  :param frozen_row: 冻结行(默认首行)
  :param frozen_col: 冻结列(默认不冻结)
  """
  # step1 判断数据正确性(每行列数是否与表头相同)
  count = 0
  for pro in data_body:
   if len(pro) != len(self.data):
    raise Exception(
     'data_body数据错误 第{}行(从0开始) 需为{}个元素 当前行{}个元素:{}'.format(count, len(self.data), len(pro), str(pro)))
   count += 1

  # step2 写入数据
  wd = xlwt.Workbook()
  sheet = wd.add_sheet(sheet_name)

  ali_horiz = 'align: horiz center' # 水平居中
  ali_vert = 'align: vert center' # 垂直居中
  fore_colour = 'pattern: pattern solid,fore_colour pale_blue' # 设置单元格背景色为pale_blue色
  # 表头格式(垂直+水平居中、表头背景色)
  style_header = xlwt.easyxf('{};{};{}'.format(fore_colour, ali_horiz, ali_vert))

  # 表体格式(垂直居中)
  style_body = xlwt.easyxf('{}'.format(ali_vert))

  # 表头
  for col in self.data:
   # 默认列宽
   if len(col) == 1:
    sheet.write(0, self.data.index(col), str(col[0]), style_header)
   # 自定义列宽
   if len(col) == 2:
    sheet.write(0, self.data.index(col), str(col[0]), style_header)
    # 设置列宽
    sheet.col(self.data.index(col)).width = 256 * col[1] # 256为基数 * n个英文字符
  # 行高(第0行)
  sheet.row(0).height_mismatch = True
  sheet.row(0).height = 20 * 20 # 20为基数 * 20榜

  # 表体
  index = 1
  for pro in data_body:
   sheet.row(index).height_mismatch = True
   sheet.row(index).height = 20 * 20 # 20为基数 * 20榜
   for d in self.data:
    value = pro[self.data.index(d)]
    # 若值类型是int、float 直接写入 反之 转成字符串写入
    if type(value) == int or type(value) == float:
     sheet.write(index, self.data.index(d), value, style_body)
    else:
     sheet.write(index, self.data.index(d), str(value), style_body)
   index += 1
  # 冻结(列与行)
  sheet.set_panes_frozen('1')
  sheet.set_horz_split_pos(frozen_row) # 冻结前n行
  sheet.set_vert_split_pos(frozen_col) # 冻结前n列

  wd.save(out_file)

 def color_test(self):
  """
  测试颜色
  """
  body_t = []
  for color in self.color_list:
   print(color)
   body_t.append(color)
  wd = xlwt.Workbook()
  sheet = wd.add_sheet('sheet')

  index = 0
  for b in body_t:
   ali = 'align: horiz center;align: vert center' # 垂直居中 水平居中
   fore_colour = 'pattern: pattern solid,fore_colour {}'.format(
    self.color_list[index][0]) # 设置单元格背景色为pale_blue色
   style_header = xlwt.easyxf(
    '{};{}'.format(fore_colour, ali))
   sheet.write(index, 0, str(b), style_header)
   sheet.col(0).width = 256 * 150 # 256为基数 * n个英文字符
   index += 1

  wd.save('颜色测试.xlsx')


# 测试颜色
# if __name__ == '__main__':
#  header_t = [
#   ['颜色']
#  ]
#  JarExcelUtil(header_t).color_test()

if __name__ == '__main__':
 header = [
  ['序号', 5],
  ['姓名', 10],
  ['性别', 10],
  ['爱好', 10],
  ['生日', 20]
 ]

 # header = [
 #  ['序号'],
 #  ['姓名'],
 #  ['性别'],
 #  ['爱好'],
 #  ['生日']
 # ]

 body = [
  [1, '张三', '男', '篮球', '1994-07-23'],
  [2, '李四', '女', '足球', '1994-04-03'],
  [3, '王五', '男', '兵乓球', '1994-09-13']
 ]

 JarExcelUtil(header_list=header).write(out_file='测试.xlsx', data_body=body)

二、效果

生成的Excel

Python xlrd/xlwt 创建excel文件及常用操作

三、常用操作

3.1、设置行高

# 行高(第0行)
sheet.row(0).height_mismatch = True
sheet.row(0).height = 20 * 20 # 20为基数 * 20榜

3.2、设置列宽

# 列宽(第0列)
sheet.col(0).width = 256 * 30 # 256为基数 * 30个英文字符(约)

3.3、冻结(列与行)

# 冻结(列与行)
sheet.set_panes_frozen('1')
sheet.set_horz_split_pos(2) # 冻结前2行
sheet.set_vert_split_pos(3) # 冻结前3列
  
# 冻结首行
sheet.set_panes_frozen('1')
sheet.set_horz_split_pos(1) # 冻结前1行(即首行)

3.4、设置单元格对齐方式

# 方式1
style_1 = xlwt.XFStyle()
al_1 = xlwt.Alignment()
al_1.horz = xlwt.Alignment.HORZ_CENTER # 水平居中
al_1.vert = xlwt.Alignment.VERT_CENTER # 垂直居中
style_1.alignment = al_1
sheet.write(0, 0, '第0行第0列单元格值', style_1)
  
# 方式2(推荐)
ali_horiz = 'align: horiz center' # 水平居中
ali_vert = 'align: vert center' # 垂直居中
style_2 = xlwt.easyxf('{};{}'.format(ali_horiz, ali_vert))
sheet.write(0, 0, '第0行第0列单元格值', style_2)

3.5、设置单元格背景色

# 设置单元格背景色
fore_colour = 'pattern: pattern solid,fore_colour pale_blue' # 设置单元格背景色为pale_blue色 (具体颜色值 参考上面代码JarExcelUtil类中的color_test方法的运行结果)
style = xlwt.easyxf('{}'.format(fore_colour))
sheet.write(0, 0, '第0行第0列单元格值', style)

以上就是Python xlrd/xlwt 创建excel文件及常用操作的详细内容,更多关于python 操作excel的资料请关注三水点靠木其它相关文章!

Python 相关文章推荐
Django的session中对于用户验证的支持
Jul 23 Python
Python多线程经典问题之乘客做公交车算法实例
Mar 22 Python
浅谈python中对于json写入txt文件的编码问题
Jun 07 Python
Python使用numpy模块创建数组操作示例
Jun 20 Python
python绘制直线的方法
Jun 30 Python
python 重命名轴索引的方法
Nov 10 Python
python 产生token及token验证的方法
Dec 26 Python
Python通过getattr函数获取对象的属性值
Oct 16 Python
运行python提示no module named sklearn的解决方法
Nov 29 Python
Python爬取酷狗MP3音频的步骤
Feb 26 Python
Python数据清洗工具之Numpy的基本操作
Apr 22 Python
python 批量压缩图片的脚本
Jun 02 Python
安装并免费使用Pycharm专业版(学生/教师)
Sep 24 #Python
Pycharm学生免费专业版安装教程的方法步骤
Sep 24 #Python
python 多线程共享全局变量的优劣
Sep 24 #Python
改变 Python 中线程执行顺序的方法
Sep 24 #Python
浅析Python 字符编码与文件处理
Sep 24 #Python
学生如何注册Pycharm专业版以及pycharm的安装
Sep 24 #Python
python判断元素是否存在的实例方法
Sep 24 #Python
You might like
php set_time_limit()函数的使用详解
2013/06/05 PHP
PHP中isset()和unset()函数的用法小结
2014/03/11 PHP
PHP图片处理之图片旋转和图片翻转实例
2014/11/19 PHP
php中 $$str 中 "$$" 的详解
2015/07/06 PHP
PHP文件缓存类实现代码
2015/10/26 PHP
php实现购物车功能(下)
2016/01/05 PHP
php实现数据库的增删改查
2017/02/26 PHP
Laravel ORM 数据model操作教程
2019/10/21 PHP
JavaScript 直接操作本地文件的实现代码
2009/12/01 Javascript
JavaScript表单验证的两种实现方法
2017/02/11 Javascript
详解如何在react中搭建d3力导向图
2018/01/12 Javascript
在小程序中使用Echart图表的示例代码
2018/08/02 Javascript
Angular angular-file-upload文件上传的示例代码
2018/08/23 Javascript
JS通过ajax + 多列布局 + 自动加载实现瀑布流效果
2019/05/30 Javascript
Vue实现穿梭框效果
2020/09/30 Javascript
vue中echarts的用法及与elementui-select的协同绑定操作
2020/11/17 Vue.js
[41:41]TFT vs Secret Supermajor小组赛C组 BO3 第一场 6.3
2018/06/04 DOTA
python基础教程之缩进介绍
2014/08/29 Python
Python获取DLL和EXE文件版本号的方法
2015/03/10 Python
python复制文件的方法实例详解
2015/05/22 Python
Python 类与元类的深度挖掘 I【经验】
2016/05/06 Python
Python 常用string函数详解
2016/05/30 Python
Django如何实现网站注册用户邮箱验证功能
2019/08/14 Python
python openvc 裁剪、剪切图片 提取图片的行和列
2019/09/19 Python
基于python解线性矩阵方程(numpy中的matrix类)
2019/10/21 Python
快速解决jupyter启动卡死的问题
2020/04/10 Python
python小程序之4名牌手洗牌发牌问题解析
2020/05/15 Python
matplotlib自定义鼠标光标坐标格式的实现
2021/01/08 Python
Fossil美国官网:Fossil手表、手袋、珠宝及配件
2017/02/01 全球购物
东南亚冒险旅行与活动:Adventoro
2019/10/16 全球购物
软件测试工程师笔试题带答案
2015/03/27 面试题
幼儿园庆六一游园活动方案
2014/01/29 职场文书
保密普查工作实施方案
2014/02/25 职场文书
我读书我快乐演讲稿
2014/05/07 职场文书
幼儿园2016年感恩节活动总结
2016/04/01 职场文书
LeetCode189轮转数组python示例
2022/08/05 Python