excel文件的读写
def read_excel(excel_file: str,sheet_name: str,row_num: int = 0,col_num:int = 0) ->str
# 4个参数,分别对应文件名称,sheet名称,行号,列号,返回值是获取到的内容
return content
def write_excel(excel_file: str,sheet_name: str,row_num: int = 0,col_num:int = 0,content: str) -> boolean
# 4个参数,分别对应文件名称,sheet名称,行号,列号,返回值是获取到的内容
# 如果文件不存在,抛出文件不存在异常,手动抛一个自定义的文件不存在的异常
#如果写入成功则返回True
return True
#如果写入失败则返回False
return False
解答:
import xlwt
import xlrd
from xlutils.copy import copy
# 4个参数,分别对应文件名称,sheet名称,行号,列号,返回值是获取到的内容
def read_excel(excel_file, sheet_name, row_num = 0,col_num = 0):
workbook = xlrd.open_workbook(excel_file) # 打开工作簿
print("读取的内容为:")
print("-----------")
if (row_num != 0 and col_num !=0):
sheets = workbook.sheet_by_index(0)
print(sheets.cell(row_num, col_num).value) # 读取指定行和列获取数据
else:
sheets = workbook.sheet_names() # 获取工作簿中的所有表格
worksheet = workbook.sheet_by_name(sheets[0]) # 获取工作簿中所有表格中的的第一个表格
for i in range(0, worksheet.nrows):
for j in range(0, worksheet.ncols):
print(worksheet.cell_value(i, j), "\t", end="") # 逐行逐列读取数据
print()
def write_excel(excel_file,sheet_name,row_num,col_num,content):
index = len(content) # 获取需要写入数据的行数
workbook = xlwt.Workbook() # 新建一个工作簿
sheet = workbook.add_sheet(sheet_name) # 在工作簿中新建一个表格
#sheet.write(row_num,col_num,content[0][0])向某行某列写入内容
for i in range(0, index):
for j in range(0, len(content[i])):
sheet.write(i, j, content[i][j]) # 像表格中写入数据(对应的行和列)
workbook.save(excel_file) # 保存工作簿
print("xls格式表格写入数据成功!")
return content
#追加内容
def write_excel_xls_append(path, value):
index = len(value) # 获取需要写入数据的行数
workbook = xlrd.open_workbook(path) # 打开工作簿
sheets = workbook.sheet_names() # 获取工作簿中的所有表格
worksheet = workbook.sheet_by_name(sheets[0]) # 获取工作簿中所有表格中的的第一个表格
rows_old = worksheet.nrows # 获取表格中已存在的数据的行数
new_workbook = copy(workbook) # 将xlrd对象拷贝转化为xlwt对象
new_worksheet = new_workbook.get_sheet(0) # 获取转化后工作簿中的第一个表格
for i in range(0, index):
for j in range(0, len(value[i])):
new_worksheet.write(i + rows_old, j, value[i][j]) # 追加写入数据,注意是从i+rows_old行开始写入
new_workbook.save(path) # 保存工作簿
print("xls格式表格【追加】写入数据成功!")
#写入内容
book_name_xls = 'xls测试格式测试工作簿.xls'
sheet_name_xls = 'xls测试格式测试表'
value_title = [["姓名", "性别", "年龄", "城市", "职业"], ]
value1 = [["张三", "男", "19", "杭州", "研发工程师"],
["李四", "男", "22", "北京", "医生"],
["王五", "女", "33", "珠海", "出租车司机"], ]
rows_num = 3
col_num = 3
write_excel(book_name_xls,sheet_name_xls,rows_num,col_num,value_title)
write_excel_xls_append(book_name_xls, value1)
#读取内容
try:
#当rows_num col_num 值为0则读取所有,否则读取指定行列内容
read_excel(book_name_xls,sheet_name_xls,rows_num,col_num)
except FileNotFoundError as e:
print("读取发生异常了")
finally:
print("---------")
print("读取完毕")