注意:
- 尽量使用xls, xlrd对xlsx支持不好。
# -*- coding: utf-8 -*-
import time
import xlrd
from xlutils.copy import copy
xls_path = '/Users/hui/Desktop/test.xls'
data = [[i for i in range(10)] for j in range(3)]
def write_date_to_xls(xls_path, data):
# 0. 基础 :
# 获取工作簿对象
wb = xlrd.open_workbook(xls_path)
# 1. 了解的内容:
# 1.1 打开excel表
sheets = wb.sheet_names()
# 1.2 获取指定的sheet---两种方式--名字 or 索引
sheet1 = wb.sheet_by_index(0)
# sheet2 = wb.sheet_by_name(sheet_name)
# 1.3 sheet 获取已经使用的行和列的索引,比实际数要小1
name, nrows, ncols = sheet1.name, sheet1.nrows, sheet1.ncols
# 1.4 一行,一列,一单元格的值
one_row_data, one_col_data, one_cell_data = sheet1.row_values(0), sheet1.col_values(0), sheet1.cell_value(0, 0)
# 2. 写入数据:
# 2.1 获取写入起始行的索引
nrows = wb.sheet_by_index(0).nrows
# 2.2 复制副本, xlrd只读,所以使用xlutils的copy
copy_wb = copy(wb)
# 2.3 获取目标sheet
target_sheet = copy_wb.get_sheet(0)
# 2.4 循环逐行写入
for row_data in data:
ncols = 0
for cell_data in row_data:
target_sheet.write(nrows, ncols, cell_data)
ncols += 1
print('write data into table..... line is {}, data is : {}'.format(nrows+1, row_data))
nrows += 1
# 2.5 保存
copy_wb.save(xls_path)
# 3. 读取数据:
# 3.1 获取当前的sheet
target_sheet = wb.sheet_by_index(0)
# 3.2 获取当前sheet的写入最大行数的索引
nrows = target_sheet.nrows
# 3.3 列表推导式,获取到所有的数据
existing_data = [target_sheet.row_values(i) for i in range(nrows)]
print(existing_data)
if __name__ == '__main__':
st_time = time.time()
write_date_to_xls(xls_path, data)
print('Time used: {}'.format(time.time() - st_time))