Python 读写Excel

一、写入

import xlwt

write_book = xlwt.Workbook(encoding='utf-8')
# cell_overwrite_ok 默认为false,这样在重复写同一个cell时会报错
write_sheet = write_book.add_sheet('list', cell_overwrite_ok=True)
write_sheet.write(0, 0, 'href')
write_sheet.write(0, 1, 'title')
write_sheet.write(1, 0, 'href1')
write_sheet.write(1, 1, 'title1')
write_sheet.write(2, 0, 'href1')
write_sheet.write(2, 1, 'title1')

write_book.save('demo1.xls')    # 保存文件, xlsx 格式不支持


二、读取

import xlrd

read_book = xlrd.open_workbook('demo1.xls')
# read_sheet = read_book.sheets()[0]             # 通过索引顺序获取
# read_sheet = read_book.sheet_by_index(0)       # 通过索引顺序获取
# read_sheet = read_book.sheet_by_name(u'list')  # 通过名称获取
read_sheet = read_book.sheet_by_name('list')

print(read_sheet.row_values(0))                  # 获取第0行
print(read_sheet.col_values(0))                  # 获取第0列
print(read_sheet.ncols)                          # 获取总列数
print(read_sheet.nrows)                          # 获取总行数
print(read_sheet.cell(1, 1).value)               # 获取对应位置的cell的值


三、修改

import xlrd
import xlwt
from xlutils3 import copy

read_book = xlrd.open_workbook('demo1.xls') # 先打开一个文件
mod_book = copy.copy(read_book)             # 然后仅仅是复制为 xlwt.Workbook 而已
mod_sheet = mod_book.get_sheet('list')      # 与get_sheet(0)相同
mod_sheet.write(1, 0, 'href111')
mod_sheet.write(1, 1, 'title1111')
mod_book.save('demo1.xls')                  # 保存文件


  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值