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