溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶(hù)服務(wù)條款》

python excel的相關(guān)操作是怎樣的

發(fā)布時(shí)間:2021-10-14 15:05:24 來(lái)源:億速云 閱讀:148 作者:柒染 欄目:編程語(yǔ)言

這期內(nèi)容當(dāng)中小編將會(huì)給大家?guī)?lái)有關(guān)python excel的相關(guān)操作是怎樣的,文章內(nèi)容豐富且以專(zhuān)業(yè)的角度為大家分析和敘述,閱讀完這篇文章希望大家可以有所收獲。

因?yàn)榻?jīng)常用到對(duì)excel的相關(guān)操作,今天給大家說(shuō)一下哈

python操作excel除了讀就是寫(xiě)。

從讀開(kāi)始

xlrd

http://pypi.python.org/pypi/xlrd

導(dǎo)入
import xlrd

打開(kāi)excel
file = xlrd.open_workbook('demo.xls')

查看文件中包含sheet的名稱(chēng)
file.sheet_names()

得到第一個(gè)工作表,或者通過(guò)索引順序 或 工作表名稱(chēng)
sheet = file.sheets()[0]
sheet = file.sheet_by_index(0)
sheet = file.sheet_by_name(u'Sheet1')

獲取行數(shù)和列數(shù)
nrows = sheet.nrows
ncols = sheet.ncols

循環(huán)行,得到索引的列表
for rownum in range(sheet.nrows):
    print sheet.row_values(rownum)

獲取整行和整列的值(數(shù)組)
sheet.row_values(i)
sheet.col_values(i)

單元格(索引獲?。?br/>cell_A1 = sheet.cell(0,0).value
cell_C4 = sheet.cell(2,3).value

分別使用行列索引
cell_A1 = sheet.row(0)[0].value
cell_A2 = sheet.col(1)[0].value

xlwt

http://pypi.python.org/pypi/xlrd

導(dǎo)入xlwt

import xlwt

新建一個(gè)excel文件

file = xlwt.Workbook() #注意這里的Workbook首字母是大寫(xiě),無(wú)語(yǔ)吧

新建一個(gè)sheet

sheet = file.add_sheet('sheet name')

寫(xiě)入數(shù)據(jù)sheet.write(行,列,value)

sheet.write(0,0,'test')

如果對(duì)一個(gè)單元格重復(fù)操作,會(huì)引發(fā)
returns error:
# Exception: Attempt to overwrite cell:
# sheetname=u'sheet 1' rowx=0 colx=0

所以在打開(kāi)時(shí)加cell_overwrite_ok=True解決

sheet = file.add_sheet('sheet name',cell_overwrite_ok=True)

保存文件

file.save('demo.xls')

另外,使用style

style = xlwt.XFStyle() #初始化樣式

font = xlwt.Font() #為樣式創(chuàng)建字體

font.name = 'Times New Roman'

font.bold = True

style.font = font #為樣式設(shè)置字體

sheet.write(0, 0, 'some bold Times text', style) # 使用樣式

xlwt 允許單元格或者整行地設(shè)置格式。還可以添加鏈接以及公式??梢蚤喿x源代碼,那里有例子:

dates.py, 展示如何設(shè)置不同的數(shù)據(jù)格式www.2cto.com

hyperlinks.py, 展示如何創(chuàng)建超鏈接 (hint: you need to use a formula)

merged.py, 展示如何合并格子

row_styles.py, 展示如何應(yīng)用Style到整行格子中.

上述就是小編為大家分享的python excel的相關(guān)操作是怎樣的了,如果剛好有類(lèi)似的疑惑,不妨參照上述分析進(jìn)行理解。如果想知道更多相關(guān)知識(shí),歡迎關(guān)注億速云行業(yè)資訊頻道。

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀(guān)點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI