xlrd/xlwt操作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
def write(self, out_file, data_body: List[list], sheet_name="sheet"):
"""
写入数据
:param out_file: 保存文件(如:test.xlsx)
:param data_body: data_body[0]为表格第0行数据 data_body[0][0]为表格第0行第0列单元格值
:param sheet_name:
"""
# 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)
# 表头
for col in self.data:
# 默认列宽
if len(col) == 1:
sheet.write(0, self.data.index(col), str(col[0]))
# 自定义列宽
if len(col) == 2:
sheet.write(0, self.data.index(col), str(col[0]))
# 设置列宽
sheet.col(self.data.index(col)).width = 256 * col[1] # 15个英文字符
# 表体
index = 1
for pro in data_body:
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)
else:
sheet.write(index, self.data.index(d), str(value))
index += 1
wd.save(out_file)
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)

![【Python】xlrd/xlwt操作excel 及常用操作[Python常见问题]](https://www.zixueka.com/wp-content/uploads/2023/10/1696831825-2d03951b87b5d34.jpg)
