汪晓康

导航

Xlrd库操作excel表格

# xlrd库操作excel表格
import xlrd
import sys

lst = __file__.split('/')[:-1]
lst.append('111.xlsx')
excelDir = '\\'.join(lst)
workbook = xlrd.open_workbook(excelDir)
# 查看存在哪些sheet表
print(workbook.sheet_names())
name1 = workbook.sheet_names()[0]
# 通过sheet名获取表格内容
workSheet = workbook.sheet_by_name(name1)
# 读取一行
rows = workSheet.row_values(0)
# 读取一格(行,列)
clos = workSheet.cell_value(4, 1)
clos1 = workSheet.cell(4, 1).value
print(rows)
print(clos)
print(clos1)
print(workSheet.cell(4, 1).ctype)

# 写入Excel表格
import xlrd
from xlutils.copy import copy
import sys

lst = __file__.split('/')[:-1]
lst.append('111.xlsx')
excelDir = '\\'.join(lst)
value = ['', 'man', 22, ',china']  # 定义需要写入的文本
rb = xlrd.open_workbook(excelDir)  # 打开一个工作薄
wb = copy(rb)  # 复制工作簿
writeSheet = wb.get_sheet(0)  # 通过get_sheet方法找到sheet页
writeSheet.write(1, 2, value[0])  # 写入单元格,1,2分别指的是单元格坐标,value[0]是具体写入的值
wb.save(excelDir)  # 最后保存工作薄
print('ok')

posted on 2021-08-09 23:26  汪晓康  阅读(124)  评论(0编辑  收藏  举报