python3:excel操作之讀取數據並返回字典 + 寫入數據

excel寫入數據,使用openpyxl庫

class WriteExcel:
    def __init__(self,path):
        self.path = path

    def write_excel(self, sheet_name, content):
        """
        在excel指定sheet中的寫入指定內容,以追加方式
        :return:
        """
        wb = openpyxl.load_workbook(self.path)
        ws = wb[sheet_name]
        # 獲取最大行
        row_num = ws.max_row
        try:
            ws.cell(row=row_num+1, column=1).value = content
        except Exception as msg:
            print('寫入excel失敗:', msg)
        finally:
            wb.save(self.path)


if __name__ == '__main__':
    WE = WriteExcel('../config/data.xlsx')
    WE.write_excel(sheet_name='user', content='瑟瑟發抖')

excel讀取數據,使用xlrd庫

class ReadExcel:
    def __init__(self,path):
        self.path = path

    def read_excel(self,row):
        """
        遍歷excel所有sheet,並以字典返回
        :param row:
        :return:
        """
        with xlrd.open_workbook(self.path, 'rb') as book:
            sheets = book.sheet_names()    # 找到所有sheets
            data_dict = {}
            for sheet in sheets:
                table = book.sheet_by_name(sheet)  # 找到要操作的sheet

                # 獲取sheet所有列數
                col_num = table.ncols
                #  讀取第一行的值,作爲每個sheet返回字典的key
                keys = table.row_values(0)

                # 讀取除指定行,作爲每個sheet返回字典的value
                values = table.row_values(row)

                # 遍歷所有列,並以字典接收,其中第一行作爲字典的key,其他行作爲字典的value
                sheet_dict = {}
                for col in range(col_num):
                    sheet_dict[keys[col]] = values[col]

            # 遍歷所有sheet,並以字典接收返回,其中sheet名稱作爲字典的key,每個sheet的數據作爲字典的value
                data_dict[sheet] = sheet_dict
        return data_dict

讀取結果:

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章