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

python辦公自動化excel

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

python怎麼讓excel自動化呢?不知道的小夥伴來看看小編今天的分享吧!

python操作excel的相關工具包可以具體到操作指定單元格的填充樣式、數值類型、數值大小等等。
1、從指定檔案路徑讀取excel表格,進行一定操作,然後儲存到另一個excel檔案:result.xlsx

import xlwtimport xlrdfrom xlutils.copy import copyimport pandas as pdfrom pandas import DataFrame,Seriesimport osos.chdir('./')# 從指定檔案路徑讀取excel表格df = pd.read_excel('D:/mypaper/data/data.xlsx')# 檢視df內容# 根據age算出出生年份,增加一列import datetimeimport osyear = datetime.datetime.now().year#獲取當前系統時間對應的年份df['birth'] = year-df['age']df.to_excel('result.xlsx')#儲存到當前工作目錄,可以用os.getcwd()檢視#檢視下此時df的內容,可以看到已經生成了birth這一列

2、單元格操作

# 定義方法:讀取指定目錄下Excel檔案某個sheet單元格的值def excel_read(file_path,table,x,y):     data = xlrd.open_workbook(file_path)     table = data.sheet_by_name(table)     return table.cell(y,x).value# 定義方法:單元格值及樣式write_obj_list = []def concat_obj(cols,rows,value):    write_obj_list.append({'cols':cols,'rows':rows,'value':value,'style':xlwt.easyxf('font: name 宋體,height 280;alignment: horiz centre')})# 定義方法:合併單元格def merge_unit(srows,erows,scols,ecols,value):    write_obj_list.append({'id':'merge','srows':srows,'erows':erows,'scols':scols,'ecols':ecols,'value':value,'style':xlwt.easyxf('font: name 宋體,height 280;alignment: horiz centre')})# 定義方法:更新excelexcel_update(file_path,write_obj_list,new_path):    old_excel = xlrd.open_workbook(file_path, formatting_info=True)    #管道作用    new_excel = copy(old_excel)    '''    透過get_sheet()獲取的sheet有write()方法    '''    sheet1 = new_excel.get_sheet(0)    '''    1代表是修改第幾個工作表裏,從0開始算是第一個。此處修改第一個工作表    '''    for item in write_obj_list:        if 'id' not in item.keys():            if 'style' in item.keys():                sheet1.write(item['rows'], item['cols'], item['value'],item['style'])            else:                sheet1.write(item['rows'], item['cols'], item['value'])        else:            if 'style' in item.keys():                sheet1.write_merge(item['srows'],item['erows'],item['scols'], item['ecols'], item['value'],item['style'])            else:                sheet1.write_merge(item['srows'],item['erows'],item['scols'], item['ecols'], item['value'])    '''    如果報錯 dict_items has no attributes sort    把syle源碼中--alist.sort() 修改爲----> sorted(alist)    一共修改2次    '''    new_excel.save(file_path)#參數詳解# srows:合併的起始行數# erows:合併的結束行數# scols:合併的起始列數# ecols:合併的結束列數# value:合併單元格後的填充值# style:合併後填充風格:#     font: name 宋體#     height 280;#     alignment: horiz centre#     ... 與excel操作基本保持一致

注意:

1、該方法僅僅是將需要直行的動作儲存到一個list中,真正的動作還未執行,執行動作是發生在excel_update方法中,最終調用excel_update方法,傳入每個單元格需要進行的操作和填充值的write_obj_list以及檔案儲存路徑file_path。就可以在當前工作目錄下生成想要的Excel結果檔案。

python辦公自動化excel

2、write_obj_list支援用戶自訂
3、write_obj_list也可以是根據excel_read方法讀取現有待修改的excel檔案(可以維持原有表格的格式)而生成