日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

python操作excel之xlwt與xlrd_python

作者:笑得好美 ? 更新時間: 2023-01-23 編程語言

xlwt與xlrd只能針對xls格式的excel進行操作,如果想對xlsx格式進行操作請使用openpyxl模板對excel進行操作

xlwt寫excel

python安裝xlwt

pip install xlwt
import xlwt

實例化工作簿對象

book = xlwt.Workbook()

xlwt創建工作表

sheet1 = book.add_sheet("姓名和電話")
???????sheet2 = book.add_sheet("詳情")

xlwt工作表中插入數據

sheet1.write(0, 0, "姓名")

xlwt設置字體樣式

#新建字體
font = xlwt.Font()
font.name = "楷體"
???????font.bold = True

創建樣式并設置

style = xlwt.XFStyle()
???????style.font = font

應用樣式

sheet1.write(0, 1, "電話", style)

xlwt批量寫入數據

for i in range(10):
    sheet1.write(i + 1, 0, f"名字{i+1}")
???????    sheet1.write(i + 1, 1, f"電話{i+1}")

xlwt保存工作簿

book.save("學生信息.xls")

xlrd讀excel

python安裝xlrd

pip install xlrd
import xlrd

xlrd打開創建已有的工作簿對象

book = xlrd.open_workbook("學生信息.xls")

xlrd獲取當前工作簿的工作表名

sheets = book.sheet_names()
print(sheets)

xlrd獲取指定的工作表

# (1)索引獲取
sheet1 = book.sheet_by_index(0)
print(sheet1)
# (2)表名獲取
sheet2 = book.sheet_by_name("詳情")
print(sheet2)

xlrd獲取表行數

rows = sheet1.nrows
print(rows)

xlrd獲取表列數

cols = sheet1.ncols
print(cols)

xlrd獲取某行的列寬

row_len = sheet1.row_len(0)
print(row_len)

xlrd獲取某行的數據(返回列表)

row_values = sheet1.row_values(1)
print(row_values)

xlrd獲取某行指定列范圍數據(參數1:行索引;參數2:起始列索引;參數3:結束列索引--不包含在內)

row_values = sheet1.row_slice(0, 0, 1)
print(row_values)

xlrd獲取某列的數據(返回列表)

col_values = sheet1.col_values(1)
print(col_values)

xlrd獲取某列指定行范圍數據(參數1:列索引;參數2:起始行索引;參數3:結束行索引--不包含在內)

col_values = sheet1.col_slice(0, 0, 11)
print(col_values)

xlrd輸出指定單元格值

cell_value = sheet1.cell(0, 1).value
print(cell_value)

原文鏈接:https://www.cnblogs.com/open-yang/p/11378294.html

欄目分類
最近更新