Python读写excel

2021-03-26  本文已影响0人  陶_306c

import xlrd
workbook = xlrd.open_workbook(r'C:\Users\zyx\Desktop\official_account.xls')
sheet = workbook.sheet_by_index(0)

#打印这一行所有内容
rows = sheet.row_values(1)
#打印这一列所有的内容
cols = sheet.col_values(2)

这里使用sheet.row_values()函数的时候必须带一个参数才能读取。列同理。
workbook.sheet_names()获取所有的sheet名称。

workbook = xlrd.open('xxx.xls')
sheet = workbook.sheet_by_name('sheet1')
nrows = sheet.nrows
ncols = sheet.ncols
for i in range(nrows):
    user_val = sheet.cell(i,0).value
    time_val = sheet.cell(i,1).value
    name_val = sheet.cell(i,2).value
    content_val = sheet.cell(i,3).value
    # 获取单元格内容
    sheet.cell(1, 0).value.encode('utf-8')
    sheet.cell_value(1, 0).encode('utf-8')
    sheet.row(1)[0].value.encode('utf-8')

给已有的excel中写入

rb = xlrd.open_workbook(filename)
wb = copy(rb)
sheet = wb.get_sheet(0)
sheet.write(m, i, value)
os.remove(filename)
wb.save(filename)

import xlwt
workbook = xlwt.Workbook(encoding='utf-8',style_compression=0)
worksheet = workbook.add_sheet('sheet',cell_overwrite_ok=True)
worksheet.write(row,col,'abc')
workbook.save('xxx.xls')
上一篇下一篇

猜你喜欢

热点阅读