1. 程式人生 > >Python 操作excel 模塊

Python 操作excel 模塊

upload a20 workbook ets 兩種 open 打開 cms 內容

在python 中操作excel表格,讀取excel 模塊常使用的是 xlrd,寫excel 模塊使用的是xlwt

  #讀取excel 表 
    import xlrd
    #打開excel
    myWorkbook = xlrd.open_workbook(‘example.xls‘)
    #獲取sheet 頁內容
mySheets = myWorkbook.sheets()
    #打印sheets 頁
    print(mySheets,type(mySheets))

    執行後結果

    [<xlrd.sheet.Sheet object at 0x0000000001463940>, <xlrd.sheet.Sheet object at 0x00000000014639E8>, <xlrd.sheet.Sheet object at 0x0000000001463A20>] <class ‘list‘>      

mySheet1 = myWorkbook.sheet_by_index(0) # 根據索引獲取sheet 頁內容
print(mySheet1)
mySheet2 = myWorkbook.sheet_by_name(u‘分組‘)
print(mySheet2)

執行後結果

<xlrd.sheet.Sheet object at 0x00000000014B3978>
<xlrd.sheet.Sheet object at 0x00000000014B3978>

#獲取行數
#mySheet1 表的行數
mySheet1 = myWorkbook.sheet_by_index(0)
MRows = mySheet1.nrows

MCows = mySheet1.ncols

mySheet1 = myWorkbook.sheet_by_index(0)
MRows = mySheet1.nrows
MCows = mySheet1.ncols
print(MRows, MCows)

#執行後結果展示
18 1 #18 行,1列

#獲取行的內容
mySheet1 = myWorkbook.sheet_by_index(0)
MRows_value = mySheet1.row_values(0) # 獲取行的內容
MCows_value = mySheet1.col_values(0) # 獲取列的內容
print(MRows_value, MCows_value)

#執行後結果展示
[‘組名‘] [‘組名‘, ‘FILE_UPLOAD_CONFIG‘, ‘TRACE_LOG_CONFIG‘, ‘TRACE_LOG_KAFKA_CONFIG‘, ‘a_howbuy‘, ‘activity-config‘, ‘auth-center‘, ‘cgi-simu‘, ‘cms‘, ‘cmsactivity‘, ‘cmsfund‘, ‘common‘, ‘config‘, ‘content‘, ‘coop-merchant‘, ‘coop-tenpay‘, ‘coop-trade‘, ‘coop-trade-apistd‘]

#獲取單元格的內容,主要有兩種方式
方式一、
my_cell_value = mySheet1.cell(0, 0) # 第一個參數是行,第二個參數是列
print(my_cell_value.value)

#執行後展示
組名

方式二、

my_cell_value3 = mySheet1.cell_value(9,0) # 第一個參數是行,第二個參數是列
print(my_cell_value3)
#執行後展示

cmsactivity

#循環遍歷單元格的內容

len_rows = mySheet1.nrows #行數

for i in range(len_rows):
print(mySheet1.cell_value(i, 0))

#執行後展示
FILE_UPLOAD_CONFIG
TRACE_LOG_CONFIG
TRACE_LOG_KAFKA_CONFIG
a_howbuy
activity-config
auth-center
cgi-simu
cms
cmsactivity
cmsfund
common
config
content
coop-merchant
coop-tenpay
coop-trade
coop-trade-apistd

Python 操作excel 模塊