Python3读取、写⼊、追加写⼊Excel⽂件⼀、需要⽤到的库:
1.操作xls格式的表格⽂件:
读取:xlrd
写⼊:xlwt
修改(追加写⼊):xlutils
2.操作xlsx格式的表格⽂件:
读取/写⼊:openpyxl
⼆、实现代码
1.操作xls格式的表格⽂件:
import xlrd
import xlwt
py import copy
def write_excel_xls(path, sheet_name, value):
index = len(value)  # 获取需要写⼊数据的⾏数
workbook = xlwt.Workbook()  # 新建⼀个⼯作簿
sheet = workbook.add_sheet(sheet_name)  # 在⼯作簿中新建⼀个表格
for i in range(0, index):
for j in range(0, len(value[i])):
sheet.write(i, j, value[i][j])  # 像表格中写⼊数据(对应的⾏和列)
workbook.save(path)  # 保存⼯作簿
print("xls格式表格写⼊数据成功!")
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 = ws  # 获取表格中已存在的数据的⾏数
new_workbook = copy(workbook)  # 将xlrd对象拷贝转化为xlwt对象
new_worksheet = _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格式表格【追加】写⼊数据成功!")
def read_excel_xls(path):
workbook = xlrd.open_workbook(path)  # 打开⼯作簿
sheets = workbook.sheet_names()  # 获取⼯作簿中的所有表格
worksheet = workbook.sheet_by_name(sheets[0])  # 获取⼯作簿中所有表格中的的第⼀个表格
for i in range(0, ws):
for j in range(0, ls):
ll_value(i, j), "\t", end="")  # 逐⾏逐列读取数据
print()
book_name_xls = 'xls格式测试⼯作簿.xls'
sheet_name_xls = 'xls格式测试表'
value_title = [["姓名", "性别", "年龄", "城市", "职业"],]
value1 = [["张三", "男", "19", "杭州", "研发⼯程师"],
["李四", "男", "22", "北京", "医⽣"],
["王五", "⼥", "33", "珠海", "出租车司机"],]
value2 = [["Tom", "男", "21", "西安", "测试⼯程师"],
["Jones", "⼥", "34", "上海", "产品经理"],
["Cat", "⼥", "56", "上海", "教师"],]
write_excel_xls(book_name_xls, sheet_name_xls, value_title)
write_excel_xls_append(book_name_xls, value1)
write_excel_xls_append(book_name_xls, value2)
python怎么读入excelread_excel_xls(book_name_xls)
2.操作xlsx格式的表格⽂件:
import openpyxl
def write_excel_xlsx(path, sheet_name, value):
index = len(value)
workbook = openpyxl.Workbook()
sheet = workbook.active
sheet.title = sheet_name
for i in range(0, index):
for j in range(0, len(value[i])):
workbook.save(path)
print("xlsx格式表格写⼊数据成功!")
def read_excel_xlsx(path, sheet_name):
workbook = openpyxl.load_workbook(path)
# sheet = wb.get_sheet_by_name(sheet_name)这种⽅式已经弃⽤,不建议使⽤    sheet = workbook[sheet_name]
for row ws:
for cell in row:
print(cell.value, "\t", end="")
print()
book_name_xlsx = 'xlsx格式测试⼯作簿.xlsx'
sheet_name_xlsx = 'xlsx格式测试表'
value3 = [["姓名", "性别", "年龄", "城市", "职业"],
["111", "⼥", "66", "⽯家庄", "运维⼯程师"],
["222", "男", "55", "南京", "饭店⽼板"],
["333", "⼥", "27", "苏州", "保安"],]
write_excel_xlsx(book_name_xlsx, sheet_name_xlsx, value3)
read_excel_xlsx(book_name_xlsx, sheet_name_xlsx)
三、运⾏结果

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。