xlrd写入excel


注意:

  1. 尽量使用xls, xlrd对xlsx支持不好。
# -*- coding: utf-8 -*-

import xlwt
import xlrd
from xlutils.copy import copy

xlspath = './demo.xlsx'
values = [['小明', '18', '男'],
          ['小李', '27', '男'],
          ['小王', '90', '女']]

# 创建excel文件, 如果已有就会覆盖
workbook = xlwt.Workbook(encoding='utf-8')
# 创建新的工作表
workbook.add_sheet('L0')
workbook.add_sheet('L1')
workbook.add_sheet('L2')
workbook.save(xlspath)

# 获取xlrd.worksheet对象使用的方法
# sheet_by_index()
# sheet_by_name()
# 获取xlwt.worksheet对象使用的方法
# get_sheet()
# 获取当前行数应该使用xlrd.worksheet的nrows  xlwt.worksheet对象没有这个属性, 所有sheet属性都需要使用xlrd模块,而不是xlwt
# demosheet.nrows

# 写入数据:
wb = xlrd.open_workbook(xlspath)
nrows = wb.sheet_by_index(0).nrows  # 当前行数

copywb = copy(wb)
copywb.add_sheet('L4')              # ------- 追加sheet
targetsheet = copywb.get_sheet(0)

for rowdata in values:
    ncols = 0
    for celldata in rowdata:
        targetsheet.write(nrows, ncols, celldata)
        ncols += 1
    print('write success --- line is {}, data is : {}'.format(nrows + 1, rowdata))
    nrows += 1
copywb.save(xlspath)  # 保存修改


# 读取数据
wb = xlrd.open_workbook(xlspath)
sheets = wb.sheet_names()
print('all sheets --- {}'.format(sheets))
# 获取目标标签页
sheet1 = wb.sheet_by_index(0)  # 获取指定的sheet---两种方式--名字 or 索引 sheet2 = wb.sheet_by_name(sheet_name)
# 获取具体的行数
name, nrows, ncols = sheet1.name, sheet1.nrows, sheet1.ncols  # sheet 获取已经使用的行和列的索引,比实际数要小1
# 获取每个单元格中的信息
one_rowdata, one_col_data, one_celldata = sheet1.row_values(0), sheet1.col_values(0), sheet1.cell_value(0, 0)  # 一行,一列,一单元格的值
print(one_rowdata, one_col_data, one_celldata)


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM