赞
踩
python 中与excel操作相关的模块:
写入数据之前,该文件一定要处于关闭状态
value = 'reslut':sh.cell(row=1,column=2,value='result')
sh = wb['sheet_name']
wb.remove(sh)
import openpyxl
# 创建一个工作簿 实例化
wb = openpyxl.Workbook()
# 创建一个test_case的sheet表单
wb.create_sheet('StudentsInfo')
# 删除默认表
sh = wb['Sheet']
wb.remove(sh)
# 保存为一个xlsx格式的文件
wb.save('批量导入用户模板.xlsx')
import openpyxl
# 第一步:打开工作簿
wb = openpyxl.load_workbook('批量导入用户模板.xlsx')
# 第二步:选取表单
sh = wb['StudentsInfo']
# 第三步:读取指定单元格
# 参数 row:行 column:列
ce = sh.cell(row = 1,column = 2) # 读取第一行,第一列的数据
print(ce.value)
输出:姓名
# 按行读取数据 list(sh.rows)
print(list(sh.rows)[1:]) # 按行读取数据,去掉第一行的表头信息数据
for cases in list(sh.rows)[1:]:
stu_id = cases[0].value
stu_name = cases[1].value
stu_sex = cases[2].value
stu_age = cases[3].value
print(stu_id, stu_name, stu_sex, stu_age)
输出:
[
(<Cell 'StudentsInfo'.A2>, <Cell 'StudentsInfo'.B2>, <Cell 'StudentsInfo'.C2>, <Cell 'StudentsInfo'.D2>),
(<Cell 'StudentsInfo'.A3>, <Cell 'StudentsInfo'.B3>, <Cell 'StudentsInfo'.C3>, <Cell 'StudentsInfo'.D3>),
(<Cell 'StudentsInfo'.A4>, <Cell 'StudentsInfo'.B4>, <Cell 'StudentsInfo'.C4>, <Cell 'StudentsInfo'.D4>),
(<Cell 'StudentsInfo'.A5>, <Cell 'StudentsInfo'.B5>, <Cell 'StudentsInfo'.C5>, <Cell 'StudentsInfo'.D5>)
]
1 大佬 男 18
2 高手 女 18
3 大神 男 19
None 6 None None
all_row = []
for cases in list(sh.rows)[1:]:
row = []
stu_id = cases[0].value
stu_name = cases[1].value
stu_sex = cases[2].value
stu_age = cases[3].value
# print(stu_id, stu_name, stu_sex, stu_age)
data = {
"stu_id": stu_id,
"stu_name": stu_name,
"stu_sex": stu_sex,
"stu_age": stu_age
}
all_row.append(data)
print(all_row)
输出:
[
{'stu_id': 1, 'stu_name': '大佬', 'stu_sex': '男', 'stu_age': 18},
{'stu_id': 2, 'stu_name': '高手', 'stu_sex': '女', 'stu_age': 18},
{'stu_id': 3, 'stu_name': '大神', 'stu_sex': '男', 'stu_age': 19},
{'stu_id': None, 'stu_name': 6, 'stu_sex': None, 'stu_age': None}
]
# 关闭工作薄
wb.close()
# 第二步:选取表单
sh = wb['StudentsInfo']
# 第一行输入
sh.append(['1', '2', '3', '6'])
from openpyxl.styles import Font, colors, Alignment
sh.sheet_properties.tabColor = "FFAA33"
下面的代码指定了等线24号,加粗斜体,字体颜色蓝色。直接使用cell的font属性,将Font对象赋值给它。
sh = wb['StudentsInfo']
bold_itatic_24_font = Font(name='等线', size=24, italic=True, color=colors.BLUE, bold=True)
sh['A1'].font = bold_itatic_24_font
也是直接使用cell的属性aligment,这里指定垂直居中和水平居中。除了center,还可以使用right、left等等参数。
sh['B1'].alignment = Alignment(horizontal='center', vertical='center')
# 第2行行高
sh.row_dimensions[2].height = 40
# C列列宽
sh.column_dimensions['C'].width = 30
sh.merge_cells('B1:G1') # 合并一行中的几个单元格
sh.merge_cells('A3:D6') # 合并一个矩形区域中的单元格
参考:
https://www.cnblogs.com/wanglle/p/11455758.html
http://www.52codes.net/develop/shell/58896.html
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。