網站首頁 學習教育 IT科技 金融知識 旅遊規劃 生活小知識 家鄉美食 養生小知識 健身運動 美容百科 遊戲知識 綜合知識
當前位置:趣知科普吧 > IT科技 > 

python操作excel表

欄目: IT科技 / 發佈於: / 人氣:1.76W

python操作excel表格是怎樣的呢?下面就讓我們一起來了解一下吧:

python操作excel一般是會用到xlrd與xlwt這兩個庫,也就是xlrd爲讀取excel,xlwt則是寫excel的庫。

不過需要先安裝好xlrd模組,可以直接到到python官網下載,當然前提是已經安裝了python環境。

此外,在單元格中的常用數據類型有0.empty(空的),1string(text),2number,3date,4boolean,5error,6blank(空白表格)。

python操作excel表

參考範例:

運用xlwt寫excel,具體指令爲:

import xlwt

#設定表格樣式

def set_style(name,height,bold=False):

style=xlwt.XFStyle()

font = xlwt.Font()

font.name = name

font.bold = bold

font.color_index = 4

font.height = height

style.font = font

return style

#寫Excel

def write_excel():

f = xlwt.Workbook()

sheet1 = f.add_sheet('學生',cell_overwrite_ok=True)

row0 = ["姓名","年齡","出生日期","愛好"]

colum0 = ["張三","李四","戀習Python","小明","小紅","無名"]

#寫第一行

for i in range(0,len(row0)):

sheet1.write(0,i,row0[i],set_style('Times New Roman',220,True))

#寫第一列

for i in range(0,len(colum0)):

sheet1.write(i+1,0,colum0[i],set_style('Times New Roman',220,True))

sheet1.write(1,3,'2006/12/12')

sheet1.write_merge(6,6,1,3,'未知')#合併行單元格

sheet1.write_merge(1,2,3,3,'打遊戲')#合併列單元格

sheet1.write_merge(4,5,3,3,'打籃球')

f.save('test.xls')

if __name__ == '__main__':

write_excel()

python操作excel表 第2張

運用xlrd讀excel,一般需要先開啟檔案,選定表格,然後讀取行列內容,再讀取表格內數據,具體指令爲:

import xlrd

from datetime import date,datetime

file = 'test3.xlsx'

def read_excel():

wb = xlrd.open_workbook(filename=file)#開啟檔案

print(wb.sheet_names())#獲取所有表格名字

sheet1 = wb.sheet_by_index(0)#透過索引獲取表格

sheet2 = wb.sheet_by_name('年級')#透過名字獲取表格

print(sheet1,sheet2)

print(sheet1.name,sheet1.nrows,sheet1.ncols)

rows = sheet1.row_values(2)#獲取行內容

cols = sheet1.col_values(3)#獲取列內容

print(rows)

print(cols)

print(sheet1.cell(1,0).value)#獲取表格裏的內容,三種方式

print(sheet1.cell_value(1,0))

print(sheet1.row(1)[0].value)

Tags:Python excel