xlwt;xlrd;xlutils;扩展包
一,安装
pip install xlwt
pip install xlrd
pip install xlutils
二,模版
# 新增Excel文件
import xlwt
workBook = xlwt.Workbook(encoding='utf-8') # 创建Excel 工作簿
workSheet = workBook.add_sheet('Movies') # 创建Excel sheet
workSheet.write(2, 2, 'Title') # 写入数据 # 第一个是行,第二个是列
workBook.save('./create_file/Movies.xls') # 保存Excel文件
# 读取Excel文件
import xlrd
workBook = xlrd.open_workbook('./create_file/Movies.xls') # 打开Excel工作簿
# print(f'Excel中有{workBook.nsheets}个工作表')
# print(f'Excel中Sheets的名字{workBook.sheet_names()}')
workSheet = workBook.sheet_by_index(0) # 选择Excel sheet
workSheet2 = workBook.sheet_by_name('Movies') # 选择Excel sheet方法二
# print('表头:', workSheet.row_values(0))
# print(f'Sheet里面一共有{workSheet.nrows}行数据 & {workSheet2.ncols}列数据')
print(f'第3行第3列的值: {workSheet.cell_value(2, 2)}') # 获取单元格的值
print(f'第3行第3列的值: {workSheet.cell(2, 2).value}')
print(f'第3行第3列的值: {workSheet.row(2)[2].value}')
print('第3行所有行的值:', workSheet.row_values(2)) # 获取整行值
print('第3行所有列的值:', workSheet.col_values(2)) # 获取整列值
for r in range(workSheet.nrows):
for c in range(workSheet.ncols):
print(f'第{r+1}行第{c+1}列的值: {workSheet.cell_value(r, c)}')
# 修改Excel文件:先打开文件,然后修改,最后保存
# 保险可以先复制一个文件出来,然后修改
import xlrd
import xlwt
from xlutils.copy import copy
workBook = xlrd.open_workbook('./create_file/Movies.xls') # 打开Excel工作簿
workSheet = workBook.sheet_by_index(0) # 选择Excel sheet
workBook2 = copy(workBook) # 复制Excel工作簿
workSheet2 = workBook2.get_sheet(0) # 选择Excel sheet
workSheet2.write(2, 2, 'Title2') # 写入数据
workSheet2_new = workBook2.add_sheet('Movies2') # 新增Excel sheet
workBook2.save('./create_file/Movies2.xls') # 保存到新Excel文件
# 修改式样
import xlwt
ft = xlwt.Font() # 设置字体属性
ft.name = '微软雅黑' # 字体
ft.colour_index = 2 # 字体颜色
ft.height = 11 * 20 # 字体大小
ft.bold = True # 是否加粗
ft.underline = True # 下划线
ft.italic = True # 斜体
# 设置单元格属性
workSheet.row(3).height_mismatch = True # 设置行高
workSheet.row(3).height = 10 * 256 # 设置行高
workSheet.col(3).width = 20 * 256 # 设置列宽
alignment = xlwt.Alignment() # 设置对齐方式
alignment.horz = 2 # 1 左,2 居中,3 右
alignment.vert = 1 # 0 上,1 中,2 下
border = xlwt.Borders() # 设置边框属性 # 细实线:1,小粗实线:2,细虚线:3,中细虚线:4,大粗实线:5,双线:6,细点虚线:7, 大粗虚线:8,细点划线:9,粗点划线:10,细双点划线:11,粗双点划线:12,斜点划线:13
border.left = 1 # 边框宽度
border.right = 1
border.top = 1
border.bottom = 1
border.left_colour = 1
border.right_colour = 2
border.top_colour = 3
border.bottom_colour = 4
pattern = xlwt.Pattern() # 设置背景颜色
pattern.pattern = xlwt.Pattern.SOLID_PATTERN
pattern.pattern_fore_colour = 5
style = xlwt.XFStyle() # 应用字体样式
style.font = ft
style.alignment = alignment
style.borders = border
style.pattern = pattern
style5 = xlwt.easyxf('font: name Arial, colour-index red; align: horiz center;') # 汇总写法
workSheet.write(2, 2, 'Title2', style5) # 写入数据