"""
Author:Ren Yulian
Create Time: 2023/2/15 17:26
Happy every day!
"""
import xlutils,xlwt,xlrd
from xlutils.copy import copy
# 1.使用xlrd打开已经存在的工作簿对象(得到一个只读的工作簿)
old_wb = xlrd.open_workbook('files/作业数据.xls', formatting_info=True)
# 2. 拷⻉原⽂件得到可写的⼯作簿对象
new_wb = copy(old_wb)
sheet0 = old_wb.sheet_by_name('原始数据')
# 3. 添加⼯作表
sheet1 = new_wb.add_sheet('效果1', cell_overwrite_ok=True)
# ==================设置单元格的样式=================
# 1.创建样式对象
style1 = xlwt.XFStyle()
style2 = xlwt.XFStyle()
style3 = xlwt.XFStyle()
style4 = xlwt.XFStyle()
style5 = xlwt.XFStyle()
# 2.添加字体样式
# 姓名列字体
font1 = xlwt.Font()
font1.name = '宋体'
font1.bold = True
font1.height = 18 * 18
font1.colour_index = 28
# 第一行字体
font2 = xlwt.Font()
font2.name = '宋体'
font2.bold = True
font2.height = 20 * 20
# 分数
font3 = xlwt.Font()
font3.name = '宋体'
font3.height = 18 * 18
# 补考
font4 = xlwt.Font()
font4.name = '宋体'
font4.height = 18 * 18
font4.colour_index = 29
# 3.添加边框样式
b1 = xlwt.Borders()
b1.bottom = b1.top = b1.right = b1.left =1
# 4.添加对齐样式
al1 = xlwt.Alignment()
al1.vert = xlwt.Alignment.VERT_CENTER
al1.horz = xlwt.Alignment.HORZ_CENTER
# 5.填充样式
p1 = xlwt.Pattern()
p1.pattern = xlwt.Pattern.SOLID_PATTERN
p1.pattern_fore_colour = 47
p2 = xlwt.Pattern()
p2.pattern = xlwt.Pattern.SOLID_PATTERN
p2.pattern_fore_colour = 43
# 姓名列样式
style1.font = font1
style1.borders = b1
style1.alignment = al1
# 第一行字体
style2.font = font2
style2.borders = b1
style2.alignment = al1
style2.pattern = p2
# 分数
style3.font = font3
style3.borders = b1
style3.alignment = al1
# 补考
style4.font = font4
style4.borders = b1
style4.alignment = al1
# 不及格
style5.font = font3
style5.borders = b1
style5.alignment = al1
style5.pattern = p1
# 写⼊数据 # 添加样式
m_r = sheet0.nrows
m_c = sheet0.ncols
# 姓名列
for row in range(1,m_r):
sheet1.write(row, 0, sheet0.cell(row, 0).value, style = style1)
# 第一行
for col in range(m_c):
sheet1.write(0, col, sheet0.cell(0, col).value,style = style2)
# 分数
for row in range(1,m_r):
for col in range(1,m_c):
sheet1.write(row, col,sheet0.cell(row, col).value,style = style3)
# 补考
if sheet0.cell(row,col).value == 0:
sheet1.write(row, col,'补考', style=style4)
elif sheet0.cell(row,col).value < 60:
sheet1.write(row, col, sheet0.cell(row, col).value, style = style5)
# 设置列的宽度和行的高度
# 1)设置列的宽度
for x in range(m_c):
sheet1.col(x).width = 30*256
# 2)设置行的高度
sheet1.row(0).height_mismatch = True # 允许指定的行可以设置高度
sheet1.row(0).height = 20*60
for x in range(1,m_r):
sheet1.row(x).height_mismatch = True # 允许指定的行可以设置高度
sheet1.row(x).height = 15*60 # 设置行的高度
new_wb.save('files/作业数据.xls')
day8-xlrd和xlwt操作excel文件作业
最新推荐文章于 2024-09-01 22:59:31 发布
该代码示例展示了如何使用Python的xlrd和xlwt库来读取、复制Excel文件,并添加新的工作表。同时,它详细演示了如何设置单元格的字体、边框、对齐和填充样式,以及如何根据条件应用不同的样式,如针对分数和补考情况。最后,调整了列宽和行高。
摘要由CSDN通过智能技术生成