python3讀取Excel 包含合併單元格

2022-07-02 14:18:13 字數 2270 閱讀 1466

#

-*- coding: utf-8 -*-

import

xlrd

import

uuid

class

student():

def__init__(self, id, **kw):

self.id =id

for k, v in

kw.items():

setattr(self, k, v)

def__str__

(self):

return

'%s(id=%s,column1=%s,column2=%s,column3=%s,column4=%s)'\

%(self.

__class__.__name__

, self.id, self.column1, self.column2, self.column3,

self.column4)

defread_excel():

#開啟檔案

workbook = xlrd.open_workbook(r'

py.xlsx')

#獲取所有sheet

print('

列印所有sheet:

', workbook.sheet_names())

sheet2 = workbook.sheet_by_index(0) #

sheet索引從0開始

rows_num =sheet2.nrows

cols_num =sheet2.ncols

for r in

range(rows_num):

#一行資料的實體類

entity_dict ={}

for c in

range(cols_num):

cell_value =sheet2.row_values(r)[c]

#print('第%d行第%d列的值:[%s]' % (r, c, sheet2.row_values(r)[c]))

if (cell_value is none or cell_value == ''

): cell_value =(get_merged_cells_value(sheet2, r, c))

#構建entity

the_key = '

column

' + str(c + 1);

#動態設定各屬性值

entity_dict[the_key] =cell_value

entity_dict['id

'] =getuuid()

stu = student(**entity_dict)

print

(stu)

defget_merged_cells(sheet):

"""獲取所有的合併單元格,格式如下:

[(4, 5, 2, 4), (5, 6, 2, 4), (1, 4, 3, 4)]

(4, 5, 2, 4) 的含義為:行 從下標4開始,到下標5(不包含) 列 從下標2開始,到下標4(不包含),為合併單元格

:param sheet:

:return:

"""return

sheet.merged_cells

defget_merged_cells_value(sheet, row_index, col_index):

"""先判斷給定的單元格,是否屬於合併單元格;

如果是合併單元格,就返回合併單元格的內容

:return:

"""merged =get_merged_cells(sheet)

for (rlow, rhigh, clow, chigh) in

merged:

if (row_index >= rlow and row_index if (col_index >= clow and col_index cell_value =sheet.cell_value(rlow, clow)

#print('該單元格[%d,%d]屬於合併單元格,值為[%s]' % (row_index, col_index, cell_value))

return

cell_value

break

return

none

defgetuuid():

return

uuid.uuid1().hex

if__name__ == "

__main__":

read_excel()

python3讀取excel內容(1)

通過python讀取excel中sheet裡邊的內容 import xlrd myfile xlrd.open workbook 1.xlsx 開啟乙個excle檔案 table myfile.sheets 0 開啟第乙個sheet nrows table.nrows 讀取該sheet的行數 for...

python3讀取網頁

網上用python讀取網頁的介紹很多,但是因為版本的問題,總是弄不對,這裡就介紹下python3讀取網頁的步驟,較少,只是為了與python2 相區別 urlopen url 另外,python中的製表符如下 在需要在字元中使用特殊字元時,python用反斜槓 轉義字元。如下表 原始字串 有時我們並...

python3進行excel操作

只要有需求,就會找出解決問題的方法 pip install xlrd 讀取 pip install xlwt 寫入 首先先初始化 import xlwt excel xlwt.workbook encoding utf 8 建立excel sheet excel.add sheet member 建...