无字天书之Python第十五页(Excel表格操作)

到此Python基础就此结束…

传送门

无字天书之Python第一页
无字天书之Python第二页
无字天书之Python第三页
无字天书之Python第四页
无字天书之Python第五页
无字天书之Python第六页
无字天书之Python第七页
无字天书之Python第八页
无字天书之Python第九页
无字天书之Python第十页
无字天书之Python第十一页
无字天书之Python第十二页
无字天书之Python第十三页
无字天书之Python第十四页

正文读

系列终结直入主题…
首先,我们需要导入xlrd第三方插件

pip install xlrd

事先准备好一个Excel表格(内容如下)
在这里插入图片描述
开始代码操作:

workbook = xlrd.open_workbook('D:\\test.xls')

注意点:上面不管是写绝对路径还是相对路径都要写对
Sheet操作

#打印所有sheet的名字
print(workbook.sheet_names())
#获取所有的sheet
print(workbook.sheets())
# 根据索引获取 sheet
print(workbook.sheet_by_index(0))
# 根据名字获取 sheet
print(workbook.sheet_by_name('ttt'))

结果自行测试
文档操作

sheet1=workbook.sheets()[0]# 0代表的是第一额Sheet表格..
# 获取行数
print(sheet1.nrows)
# 获取列数
print(sheet1.ncols)

获取整行的数据和整列的数据

print(sheet1.row_values(1))# 后面的数字代表几就是几
print(sheet1.col_values(2))

获取单元格的数据

cell1=sheet1.cell(1,1).value
print(cell1)
# 行索引
cell2=sheet1.row(2)[1].value
print(cell2)
cell3=sheet1.cell(1,2).value
print(cell3)
# 列索引
cell4=sheet1.col(3)[1].value
print(cell4)

结果自己测试…

正文写

导入第三方模块

pip install xlrxwriter

创建一个

# 创建一个WorkBook
workbook =xlsxwriter.Workbook('D:\\testttt.xls')
sheet1=workbook.add_worksheet('tetttsheet')
workbook.close()

在这里插入图片描述
开始写入:

# 数据写入Excel中
#首先我们可以先设置一些的单元格的格式
workfomat=workbook.add_format()
#字体加粗
workfomat.set_bold(True)
# 单元格边框宽度
workfomat.set_border(1)
# 对齐方式
workfomat.set_align('left')
# 格式化数据格式为小数点后两位
workfomat.set_num_format('0.00')
hehehe=['onlyK', 12.0, 45.0, 78.0]
date=[['onlyK', 12.0, 45.0, 78.0],['onlyKK', 12.0, 45.0, 78.0],['onlyKKK', 12.0, 45.0, 78.0]]
sheet1.write_row('A1',hehehe,workfomat)
sheet1.write_row('A2', date[0], workfomat)
sheet1.write_row('A3', date[1], workfomat)
sheet1.write_row('A4', date[2], workfomat)

在这里插入图片描述
插入图片

# 插入图片
# 语法
# insert_image(row, col, image[, options])
# row:行坐标,起始索引值为0;
# col:列坐标,起始索引值为0;
# image:string类型,是图片路径;
# options:dict类型,是可选参数,用于指定图片位置,如URL等信息;

sheet1.insert_image('I6','F:\\fb10b464903aa2c.jpg')

在这里插入图片描述
更多学习关于Excel
end…

猜你喜欢

转载自blog.csdn.net/weixin_44255950/article/details/104575611