python xlrd xlwt 表格线有问题_【Python】xlrd/xlwt操作excel 及常用操作

"""-*- coding:utf-8 -*-

@Time :2020/8/20 21:02

@Author :Jarvis

@File :jar_excel_util.py

@Version:1.0"""

from typing importListimportxlwtclassJarExcelUtil: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_listdef 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 =0for pro indata_body:if len(pro) !=len(self.data):raiseException("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 inself.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 indata_body:for d inself.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+= 1wd.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,表格线有问题)