python-Excel讀取-合並單元格讀取


python-Excel讀取-合並單元格讀取(后續會補充python-Excel寫入的部分

 

1. python讀取Excel單元格

代碼包含讀取Excel中數據,以及出現橫向合並單元格,以及豎向合並單元格的內容。英文注釋標注了函數的功能,后又補充了部分中文注釋。

合並單元格的函數通用,可以直接復制拿走,傳入的參數為Excel某sheet表中的數據。

兩個列表合並為一個字典函數list_dic(list1,list2)也可以直接復制拿走,傳入的參數為兩個列表,list1准備作為key,list2准備作為value,key和value位置一一對應。

__author__ = 'sitong'
# !_*_coding:utf-8_*_
import xlrd
apply_dic = []
def get_excel():
    with xlrd.open_workbook(r'D:\0325.xlsx') as workbook :
        name_sheets = workbook.sheet_names() #獲取Excel的sheet表列表,存儲是sheet表名
        for index in name_sheets: #for 循環讀取每一個sheet表的內容
            sheet_info = workbook.sheet_by_name(index) #根據表名獲取表中的所有內容,sheet_info也是列表,列表中的值是每個單元格里值
            first_line = sheet_info.row_values(0) #獲取首行,我這里的首行是表頭,我打算用表頭作為字典的key,每一行數據對應表頭的value,每一行組成一個字典
            values_merge_cell = merge_cell(sheet_info) #這里是調用處理合並單元格的函數
            for i in range(1, sheet_info.nrows): #開始為組成字典准備數據
                other_line = sheet_info.row_values(i)
                for key in values_merge_cell.keys():
                    if key[0] == i:
                        other_line[key[1]] = values_merge_cell[key]
                #print(other_line)
                dic = list_dic(first_line,other_line)  #調用組合字典的函數,傳入key和value,字典生成
                apply_dic.append(dic)
            return apply_dic

def list_dic(list1,list2):
    '''
    two lists merge a dict,a list as key,other list as value
    :param list1:key
    :param list2:value
    :return:dict
    '''
    dic = dict(map(lambda x,y:[x,y], list1,list2))
    return dic

def merge_cell(sheet_info):
    '''
    #handle Merge transverse cells and handle Merge Vertical Cells, assign empty cells,
    :param rlow:row, include row exclusive of row_range
    :param rhigh:row_range
    :param clow:col, include col exclusive of col_range
    :param chigh:col_range
    :param sheet_info:object of sheet
    :return:dic contain all of empty cells value
    '''
    merge = {}
    merge_cells = sheet_info.merged_cells
    for (rlow, rhigh, clow, chigh) in merge_cells:
        value_mg_cell = sheet_info.cell_value(rlow, clow)
        if rhigh-rlow == 1:
            # Merge transverse cells
            for n in range(chigh-clow-1):
                merge[(rlow, clow+n+1)] = value_mg_cell
        elif chigh-clow == 1:
            # Merge Vertical Cells
            for n in range(rhigh-rlow-1):
                merge[(rlow+n+1, clow)] = value_mg_cell
    return merge

if __name__ == '__main__':
    get_excel()

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM