使用xlrd库处理excel文件
1
、读取
import xlrd
def get_all_sheets(path):
'''获取到所有的sheet名'''
data = xlrd.open_workbook(path)
sheet_names = data.sheet_names()
for s in sheet_names:
print(s)
def get_sheet_by_index(path, index):
'''根据sheet索引获取sheet对象'''
data = xlrd.open_workbook(path)
sheet = data.sheet_by_index(index)
rows = sheet.nrows # 获取行数
cols = sheet.ncols # 获取列数
row = []
for r in range(rows):
col = []
for c in range(cols):
col.append(sheet.cell_value(r, c))
row.append(col)
for i in row:
print(i)
def get_sheet_by_name(path, name):
'''根据sheet名获取sheet对象'''
data = xlrd.open_workbook(path)
sheet = data.sheet_by_name(name)
rows = sheet.nrows
cols = sheet.ncols
for r in range(rows):
print(sheet.row_values(r))
for c in range(cols):
print(sheet.col_values(c))
2
、说明
data.sheet_names()
获取所有的
sheet
名
data.sheet_by_index(index)
根据索引获取
sheet
data.sheet_by_name(name)
根据名称获取
sheet
sheet.nrows
获取行数
sheet.ncols
获取列数
3
、修改
excel
1
、使用
xlrd+xlutils
修改
excel
import xlrd
from xlutils.copy import copy
workbook = xlrd.open_workbook('test.xlsx')
workbooknew = copy(workbook)
ws = workbooknew.get_sheet(0)
ws.write(1, 1, 'changed!')
workbooknew.save('test3.xlsx')
2
、使用
openpyxl
修改
excel
from openpyxl import load_workbook
workbook_ = load_workbook('test.xlsx')
sheetnames = workbook_.sheetnames
sheet = workbook_[sheetnames[0]]
sheet['B4'] = 56
workbook_.save('test2.xlsx')
3
、说明
第一种方法修改后不会保存
excel
的格式,第二种不会影响
excel
格式
使用xlwt库处理excel文件
1
、写入
import xlwt
# 创建一个workbook对象
book = xlwt.Workbook(encoding='utf-8')
# 创建一个sheet
sheet = book.add_sheet('sheet')
# 添加数据
sheet.write(0, 0, 'hello')
sheet.write(0, 1, 'world')
# 保存到指定文件中
book.save('test2.xlsx')