import xlrd
from xlutils.copy import copy
import xlwt
def write_excel(filename, sheet_name, sheet_index, words):
"""
param:filename, 文件名称
param:sheet_name, 页签名称
param:sheet_index, 页签序号,从0开始
param: words, 写入的页签及对应页签中一行的值,格式 [{"表头名称1":"输入内容1"}, {"表头名称2":"输入内容2"}, ......]
"""
try:
old_excel = xlrd.open_workbook(filename) # 打开excel
work_sheet = old_excel.sheet_by_name(sheet_name) # 读取sheet 页
now_numbers = work_sheet.nrows # 获取现有行
heads = work_sheet.row_values(0) # 获取sheet页第0行的值,即表头的值
new_excel = copy(old_excel) # copy一个新的excel对象, 使对象xlrd变为xlwt
print(new_excel)
new_sheet = new_excel.get_sheet(sheet_index) # 新建一个sheet
i = now_numbers
for j in range(len(words)):
w = words[j][heads[j]] # 得到对应列的值
new_sheet.write(i, j, w) # 写入新的sheet页
new_excel.save(filename)
except Exception as e:
print(e)
write_excel("studentee3.xlsx", "sheet1", 0, [
{"FBillHead(GL_VOUCHER)": "*单据头(序号)"},
{"FAccountBookID": "*(单据头)账簿#编码"}])
前提是已经存在的表里已经写好表头