<kbd id="afajh"><form id="afajh"></form></kbd>
<strong id="afajh"><dl id="afajh"></dl></strong>
    <del id="afajh"><form id="afajh"></form></del>
        1. <th id="afajh"><progress id="afajh"></progress></th>
          <b id="afajh"><abbr id="afajh"></abbr></b>
          <th id="afajh"><progress id="afajh"></progress></th>

          openpyxl庫,1秒合并多張表格并設(shè)置圖表格式

          共 6781字,需瀏覽 14分鐘

           ·

          2021-10-12 22:55

          在日常辦公中,我們經(jīng)常有這樣的需求,需要重復(fù)的合并表格數(shù)據(jù),如果數(shù)據(jù)表不多,通常復(fù)制粘貼就足夠了,要是有成百上千的表格需要合并,普通的Ctrl+C、Ctrl+V已經(jīng)難以實現(xiàn),那么就要考慮用代碼去合并。

          這里給大家介紹兩個Python庫,用于表格的數(shù)據(jù)合并,以及解決代碼合并后,圖表樣式固定的問題,第一個OS庫,用于遍歷文件目錄,第二個openpyxl庫用來操作表格,下面逐一介紹這兩個庫的功能。

          OS模塊


          這里先介紹OS模塊的功能,因為在調(diào)用的時候,涉及的參數(shù)不多,通常都只有一行代碼,總結(jié)常用的功能如下。

          os.getcwd()

          得到當前工作目錄,即當前Python腳本工作的目錄路徑。

          os.listdir()

          返回指定目錄下的所有文件和目錄名。
          os.remove()
          用來刪除一個文件。
          os.removedirs(rc:\python”)
          刪除多個目錄。
          os.path.isfile()
          檢驗給出的路徑是否是一個文件。
          os.path.isdir()
          檢驗給出的路徑是否是一個目錄。
          os.path.exists()
          檢驗給出的路徑是否真地存在。
          os.path.dirname()
          獲取路徑名。
          os.path.abspath()
          獲得絕對路徑。
          os.path.basename()
          獲取文件名。
          os.system()
          運行shell命令。
          os.rename(old,new)
          重命名。
          os.makedirs(r”c:\python\test”)
          創(chuàng)建多級目錄。
          os.mkdir(“test”)
          創(chuàng)建單個目錄。
          os.stat(file)
          獲取文件屬性。
          os.path.getsize(filename)
          獲取文件大小。


          openpyxl模塊


          openpyxl庫用于操作表格,功能包括新建一個空的表格、給表格添加數(shù)據(jù)、導(dǎo)入數(shù)據(jù)表、遍歷數(shù)據(jù)表內(nèi)容、合并多個表格以及修改單元格格式等。

          創(chuàng)建一個空的表格

          如何使用python創(chuàng)建一個空的表格,這里使用openpyxl庫,包含創(chuàng)建表格,更改表名以及保存空表。
          from openpyxl import Workbook#創(chuàng)建表格wb=Workbook()
          #獲取當前active的sheetsheet=wb.active
          #查看sheet名sheet.title
          #改sheet名sheet.title="表格一"
          #保存表wb.save(r"C:\Users\尚天強\Desktop\測試.xlsx")
          通過上面的代碼,我們成功在桌面新建了一個名叫測試的工作簿,里面有一張名叫表格一的sheet表。

          打開已經(jīng)存在目錄中的表

          除了新建一張空的表,還可以使用命令打開已經(jīng)存在的表格數(shù)據(jù)。

          #打開一個存在的表from?openpyxl?import?load_workbookwb2=load_workbook(r"C:\Users\尚天強\Desktop\2017年銷售明細\銷售明細第1季度.xlsx"")
          向表格中寫入數(shù)據(jù)
          向空表中寫入數(shù)據(jù)有三種方式,可以依次向單元格填寫,也可以按照附加行的方式進行填寫,填寫的效果如下所示。
          from openpyxl import Workbookimport datetime#創(chuàng)建表格wb=Workbook()#獲取當前active的sheetsheet=wb.active
          #方式一:數(shù)據(jù)可以直接分配到單元格中(可以輸入公式)sheet["A1"]="李明"sheet["B2"]="小紅"sheet["C3"]="小王"
          #方式二:可以附加行,從第一列開始附加(從最下方空白處,最左開始)(可以輸入多行)sheet.append(["張三","李四","王五"])
          #方式三:Python類型會被自動轉(zhuǎn)換sheet["A5"]=datetime.datetime.now().strftime("%Y-%m-%d")
          #保存表wb.save(r"C:\Users\尚天強\Desktop\測試.xlsx")

          獲取已有表格中的數(shù)據(jù)

          要打開一張表,可以先查看這張表的所有sheet名,對sheet賦值,然后獲取對應(yīng)的值,這里得出一月這張表中A1單元格中的值。
          from openpyxl import load_workbookwb2=load_workbook(r"C:\Users\尚天強\Desktop\2017年銷售明細\銷售明細第1季度.xlsx")
          #查看sheet名wb2.sheetnames
          #獲取一月這張表sheet=wb2.get_sheet_by_name("一月")
          #查看第一張表中A1單元格中的值sheet["A1"].value
          '銷售日期'
          借助for循環(huán)導(dǎo)入A1到A5單元格中的值。
          #打印一列值for cell in sheet["A1:A5"]:     print(cell[0].value)

          導(dǎo)入全部數(shù)據(jù)

          如果要導(dǎo)入單元格中的全部數(shù)據(jù),需要先遍歷所有的行,然后遍歷所有的單元格,數(shù)據(jù)導(dǎo)入結(jié)果如下所示。
          #打印全部值for row in sheet:    for cell in row:        print(cell.value,end=",")    print()#換行

          導(dǎo)入指定行數(shù)據(jù)
          指定導(dǎo)入數(shù)據(jù)的行數(shù)和列數(shù),這里限定導(dǎo)入前五行和前五列數(shù)據(jù),數(shù)據(jù)結(jié)果如下所示。
          #遍歷指定行,第1行開始至第5行,每行打印5列for row in sheet.iter_rows(min_row=0,max_row=5,max_col=5):    for cell in row:        print(cell.value,end=",")    print()

          導(dǎo)入全部列數(shù)據(jù)
          導(dǎo)入全部的列數(shù)據(jù),需要先遍歷所有的列,然后遍歷所有的單元格,數(shù)據(jù)導(dǎo)入結(jié)果如下。
          #遍歷全部列for column in sheet.columns:    for cell in column:        print(cell.value,end=",")    print()

          導(dǎo)入指定列數(shù)據(jù)
          導(dǎo)入指定的列數(shù)據(jù),在參數(shù)中限定最小和最大列數(shù),以及最小和最大行數(shù),數(shù)據(jù)導(dǎo)入結(jié)果如下所示。
          #遍歷指定幾列的數(shù)據(jù)for col in sheet.iter_cols(min_col=2,max_col=5,min_row=3,max_row=5):    for i in col:        print(i.value,end=",")    print()

          刪除工作表

          若要刪除工作表,有remove和del兩種方式。

          #刪除工作表#方式一wb.remove(sheet)
          #方式二del wb[sheet]

          設(shè)置表格樣式

          設(shè)置表格的樣式,通常會設(shè)置表格的字體、字號大小、顏色、表格邊框、行高、列寬、字體位置等,這部分的參數(shù)設(shè)置較為瑣碎,這里舉例常用的幾個參數(shù)設(shè)置,結(jié)果如下所示。

          #導(dǎo)入包from openpyxl.styles import Font,colors,Alignment,Border,Sidefrom openpyxl import load_workbook
          wb=load_workbook(r"C:\Users\尚天強\Desktop\測試.xlsx")
          #獲取當前active的sheetsheet=wb.active

          #設(shè)置字體樣式sheet['A1'].font=Font(name='微軟雅黑',size=10,italic=False,color=colors.BLUE,bold=True)
          #設(shè)置A1中的數(shù)據(jù)垂直居中和水平居中sheet['A1'].alignment=Alignment(horizontal='center',vertical='center')
          #第2行行高sheet.row_dimensions[2].height=15
          #C列列寬sheet.column_dimensions["C"].width=20
          #設(shè)置邊框border=Border(left=Side(border_style='medium',color=colors.BLACK), right=Side(border_style='medium',color=colors.BLACK),??????????????top=Side(border_style='medium',color=colors.BLACK),???????????????bottom=Side(border_style='medium',color=colors.BLACK),???????????????diagonal=Side(border_style='medium',color=colors.BLACK),???????????????diagonal_direction=0,???????????????outline=Side(border_style='medium',color=colors.BLACK),??????????????vertical=Side(border_style='medium',color=colors.BLACK),???????????????horizontal=Side(border_style='medium',color=colors.BLACK))??????????????
          sheet["B4"].border=border???
          #保存表wb.save(r"C:\Users\尚天強\Desktop\測試.xlsx")


          分析實例


          以上部分,逐一介紹了openpyxl部分庫的功能,下面舉一個實例進行表格的合并以及格式的設(shè)置,如下是2017年的銷售明細,包含2017年4個季度的銷售數(shù)據(jù)明細。

          且每一個季度銷售數(shù)據(jù)里又包含三個月的具體明細,現(xiàn)在需要批量合并4個工作簿,共計12張表,使用Ctrl+C、Ctrl+V功能已經(jīng)不能很好的解決這里的問題,需要用代碼解決。

          這里首先使用os庫,循環(huán)遍歷該文件下的目錄,使用openpyxl庫循環(huán)遍歷單元格中的數(shù)據(jù),并且導(dǎo)入,合并結(jié)果如下,共計合并14283行記錄。

          from openpyxl import Workbook,load_workbookimport os
          def concat_data(file_path,save_path): files_name=os.listdir(file_path) #創(chuàng)建新表格 new_wb=Workbook() new_ws=new_wb.active header=['銷售日期', '員工工號', '銷售員', '貨號', '銷售單編號', '銷量', '銷售額'] new_ws.append(header) #向新的表格寫入數(shù)據(jù) for file_name in files_name: wb=load_workbook(file_path+"\\"+file_name) for sheet in wb.sheetnames: ws=wb[sheet] for row in ws.iter_rows(min_row=2,values_only=True): new_ws.append(row) #數(shù)據(jù)保存 new_wb.save(save_path+"\\"+"數(shù)據(jù)合并.xlsx")
          concat_data(r"C:\Users\尚天強\Desktop\2017年銷售明細",r"C:\Users\尚天強\Desktop")

          同時給表格設(shè)置固定的圖表樣式,其中的單元格屬性值可以直接進行修改。
          from openpyxl import Workbook,load_workbookfrom openpyxl.styles import Font,PatternFill,Alignment,Border,fills,colors,Side
          #導(dǎo)入表格數(shù)據(jù)wb=load_workbook(r"C:\Users\尚天強\Desktop\數(shù)據(jù)合并.xlsx")
          #操作單元格ws=wb.active
          #調(diào)整列寬ws.column_dimensions["A"].width=25ws.column_dimensions["B"].width=10ws.column_dimensions["C"].width=10ws.column_dimensions["D"].width=13ws.column_dimensions["E"].width=35ws.column_dimensions["F"].width=8ws.column_dimensions["G"].width=10
          #設(shè)置單元格格式#設(shè)置字體格式font=Font("微軟雅黑",size=12,color=colors.BLACK,bold=False)
          #單元格顏色填充fill=PatternFill(fill_type="solid",start_color="CDCDCD",end_color="CDCDCD") #CDCDCD淺灰色
          #單元格對齊方式alignment=Alignment(horizontal="center",vertical="center",indent=0) #wrap_text=True文字換行,shrink_to_fit=True自適應(yīng)寬度
          #單元格邊框bd=Border(left=Side(border_style="thin",color=colors.BLACK), right=Side(border_style="thin",color=colors.BLACK), top=Side(border_style="thin",color=colors.BLACK), bottom=Side(border_style="thin",color=colors.BLACK), outline=Side(border_style="thin",color=colors.BLACK), vertical=Side(border_style="thin",color=colors.BLACK), horizontal=Side(border_style="thin",color=colors.BLACK) )
          #遍歷數(shù)據(jù)for irow,row in enumerate(ws.rows,start=1): font=font fill=fill alignment=alignment border=bd for cell in row: cell.font=font cell.fill=fill cell.alignment=alignment cell.border=bd #設(shè)置表頭字體格式ft=Font("宋體",size=12,color=colors.BLUE,bold=True)#italic=True斜體ws["A1"].font=ftws["B1"].font=ftws["C1"].font=ftws["D1"].font=ftws["E1"].font=ftws["F1"].font=ftws["G1"].font=ft
          #保存數(shù)據(jù)wb.save(r"C:\Users\尚天強\Desktop\[格式調(diào)整]數(shù)據(jù)合并.xlsx")


          各位伙伴們好,詹帥本帥假期搭建了一個個人博客和小程序,匯集各種干貨和資源,也方便大家閱讀,感興趣的小伙伴請移步小程序體驗一下哦?。g迎提建議)

          推薦閱讀


          牛逼!Python常用數(shù)據(jù)類型的基本操作(長文系列第①篇)

          牛逼!Python的判斷、循環(huán)和各種表達式(長文系列第②篇)

          牛逼!Python函數(shù)和文件操作(長文系列第③篇)

          牛逼!Python錯誤、異常和模塊(長文系列第④篇)


          瀏覽 40
          點贊
          評論
          收藏
          分享

          手機掃一掃分享

          分享
          舉報
          評論
          圖片
          表情
          推薦
          點贊
          評論
          收藏
          分享

          手機掃一掃分享

          分享
          舉報
          <kbd id="afajh"><form id="afajh"></form></kbd>
          <strong id="afajh"><dl id="afajh"></dl></strong>
            <del id="afajh"><form id="afajh"></form></del>
                1. <th id="afajh"><progress id="afajh"></progress></th>
                  <b id="afajh"><abbr id="afajh"></abbr></b>
                  <th id="afajh"><progress id="afajh"></progress></th>
                  天天色啪 | 国产福利在线视频 | 日韩无码 波多野结衣 | 草逼网站免费观看 | 欧美日韩激情四射 |