xlrd写入excel
作者:互联网
import xlrd
from xlutils.copy import copy
xlsx_path = '/Users/hui/Desktop/test.xlsx'
data = [[i for i in range(10)] for j in range(3)]
def write_date_to_xlsx(xlsx_path, data):
print(xlsx_path)
print(data)
# 1. 打开excel表
wb = xlrd.open_workbook(xlsx_path)
sheets = wb.sheet_names()
print(sheets)
# 2. 获取指定的sheet
sheet1 = wb.sheet_by_index(0)
sheet2 = wb.sheet_by_name('school_sheet')
print(sheet1, sheet2)
# 3. sheet对象的属性, 行和列是已经使用的
name, nrows, ncols = sheet1.name, sheet1.nrows, sheet1.ncols
print(name, nrows, ncols)
# 4. 取某一行或者某一列的值
print(sheet1.row_values(0), sheet1.col_values(0), sheet1.cell_value(0, 0))
wb = xlrd.open_workbook(xlsx_path)
# 5. 写入数据
# 获取目前的行、列情况,必须使用wb对象,获取nrows
nrows = wb.sheet_by_index(0).nrows
# 复制副本
copy_xlsx = copy(wb)
# 打开sheet,targe_sheet仅用于写入数据
target_sheet = copy_xlsx.get_sheet(0)
# 循环逐行写入
for row_data in data:
ncols = 0
for cell_data in row_data:
target_sheet.write(nrows, ncols, cell_data)
ncols += 1
nrows += 1
# 保存
copy_xlsx.save(xlsx_path)
if __name__ == '__main__':
write_date_to_xlsx(xlsx_path, data)
标签:xlsx,sheet,wb,excel,写入,nrows,sheet1,xlrd,data 来源: https://www.cnblogs.com/hui-code/p/13473438.html