python 09篇 操作Excel

一、往Excel中写数据

  使用pip install xlwt安装xlwt模块,用xlwt模块进行对Excel进行写数据。

import xlwt

# book = xlwt.Workbook()
# sheet = book.add_sheet('students')
#
# sheet.write(0, 0, 'id')
# sheet.write(0, 1, 'name')
# sheet.write(0, 2, 'age')
#
# sheet.write(1, 0, '1')
# sheet.write(1, 1, 'xiaohei')
# sheet.write(1, 2, '18')
#
# book.save('students.xls')  # 如果后缀是xlsx,用微软的office打不开

stus = [
    [1,'ds','bejing',51],
    [2,'fd','shanghai',28],
    [3,'zc','shanghai',16],
    [4,'lhy','shanghai',21],
    [5,'ylm','shanghai',35],
    [6,'wxl','beijing',16],
]
stus.insert(0, ['编号', '姓名', '地址', '年龄'])
book = xlwt.Workbook()
sheet = book.add_sheet('sheet1')
# 第一种写法
# row = 0
# for stu in stus:
#     col = 0
#     for s in stu:
#         sheet.write(row, col, s)
#         col += 1
#     row += 1
# 第二种写法
for row,stu in enumerate(stus):
    for col,s in enumerate(stu):
        sheet.write(row, col, s)

ages = [s[-1] for s in stus if type(s[-1]) != str]
avg_age = round(sum(ages) / len(ages), 2)
sheet.write(row+1, 0, '平均年龄')
sheet.write(row+1, 1, avg_age)
book.save('students.xls')

二、读取Excel中的数据

  使用pip install xlwt安装xlrd模块,用xlrd模块进行对Excel进行读取数据。

import xlrd

book = xlrd.open_workbook('students.xls')
# sheet = book.sheet_by_index(0)
sheet = book.sheet_by_name('students')

print(book.sheets())  # 所有的sheet页,返回的是一个list,list里面是每个sheet对象

for s in book.sheets():
    print(s.row_values(1))

print(sheet.cell(0, 0).value)
print(sheet.row_values(0))
print(sheet.row_values(1))

print(sheet.col_values(0))
print(sheet.col_values(1))

print(sheet.nrows)  # 多少行
print(sheet.ncols)  # 多少列

三、修改Excel

  使用pip install xlutils 安装xlutils 模块,用xlutils 中的copy进行复制Excel,用xlrd模块进行对Excel进行读取数据,用copy的数据进行修改。

# 修改Excel, 在copy的sheet进行修改
from xlutils import copy
import xlrd

book = xlrd.open_workbook('students.xls')
sheet = book.sheet_by_index(0)
new_book = copy.copy(book)
copy_sheet = new_book.get_sheet(0)

for row in range(1, sheet.nrows-1):
    addr = sheet.cell(row, 2).value
    addr = addr.replace('beijing', '北京').replace('shanghai', '上海')
    copy_sheet.write(row, 2, addr)

new_book.save('students.xls')
原文地址:https://www.cnblogs.com/lhy-qingqiu/p/13649268.html