pandas ExcelWriter定制格式(定制表頭、渲染顏色等,非ExcelWriter標(biāo)準(zhǔn)的創(chuàng)建模式)
ExcelWriter這個(gè)插件有個(gè)坑,就是已經(jīng)設(shè)置好的格式是無(wú)法更改的,因此,由pandas轉(zhuǎn)成excel的時(shí)候,必須將格式清除,尤其是表頭的格式,代碼如下:文章源自四五設(shè)計(jì)網(wǎng)-http://m.133122.cn/39759.html
1 2 | import pandas.io.formats.excelpandas.io.formats.excel.header_style = None |
標(biāo)準(zhǔn)的保存pandas表到excel的形式為:文章源自四五設(shè)計(jì)網(wǎng)-http://m.133122.cn/39759.html
1 2 3 4 | writer = pd.ExcelWriter(output_prefix + cv_excel_file_name)df.to_excel(writer, 'Sheet1')? # 這里假設(shè)df是一個(gè)pandas的dataframewriter.save()writer.close() |
如果要定制輸出的excel格式,那么得在to_excel和save之間添加代碼:文章源自四五設(shè)計(jì)網(wǎng)-http://m.133122.cn/39759.html
1 2 3 4 5 6 7 8 9 10 | writer = pd.ExcelWriter(output_prefix + cv_excel_file_name)df.to_excel(writer, 'Sheet1')? # 這里假設(shè)df是一個(gè)pandas的dataframe# =================== add self define code here =======================# from xlsxwriter.workbook import Workbook# from xlsxwriter.worksheet import Worksheetworkbook1 = writer.bookworksheets = writer.sheetsworksheet1 = worksheets['Sheet1']writer.save()writer.close() |
有了相應(yīng)的workbook和worksheet對(duì)象,我們就可以參照官方教程來(lái)定制我們的輸出excel格式了!文章源自四五設(shè)計(jì)網(wǎng)-http://m.133122.cn/39759.html
我們?cè)诓僮鱳orksheet中的各自前,需要往workbook當(dāng)中添加自定義格式集合:文章源自四五設(shè)計(jì)網(wǎng)-http://m.133122.cn/39759.html
1 2 | format1 = workbook1.add_format({'bg_color': '#FFC7CE', 'font_color': '#9C0006'})format2 = workbook1.add_format({'bold':? True, 'align': 'left', 'valign': 'top', 'text_wrap': True}) |
文章源自四五設(shè)計(jì)網(wǎng)-http://m.133122.cn/39759.html
增:
新增格式:文章源自四五設(shè)計(jì)網(wǎng)-http://m.133122.cn/39759.html
1 2 3 4 5 6 7 8 | bold = f.add_format({????????'border': 1,? # 單元格邊框?qū)挾?/code>????????'align': 'left',? # 水平對(duì)齊方式????????'valign': 'vcenter',? # 垂直對(duì)齊方式????????'fg_color': '#F4B084',? # 單元格背景顏色????????'text_wrap': True,? # 是否自動(dòng)換行????}) |
新增單元格數(shù)據(jù):文章源自四五設(shè)計(jì)網(wǎng)-http://m.133122.cn/39759.html
1 2 | //row:行, col:列, data:要寫(xiě)入的數(shù)據(jù), bold:單元格的樣式worksheet1.write(row, col, data, bold) |
刪:
改(這里主要介紹改的方法):
設(shè)置列寬和顏色:文章源自四五設(shè)計(jì)網(wǎng)-http://m.133122.cn/39759.html
1 2 | yellow = workbook1.add_format({'fg_color': '#FFEE99'})worksheet1.set_column("E:E", 16, cell_format=yellow) |
設(shè)置列寬(B列到ae列所有的列寬都為16):文章源自四五設(shè)計(jì)網(wǎng)-http://m.133122.cn/39759.html
1 | worksheet1.set_column("B:AE", 16) |
設(shè)置條件格式(令A(yù)列2到55行選出數(shù)值最大的一個(gè)‘top1’,并用format1的格式和顏色進(jìn)行渲染):
1 | worksheet1.conditional_format('A2:A55', {'type': 'top', 'value': 1, 'format': format1}) |
設(shè)置行格式(更改表頭格式):
1 | worksheet1.set_row(0, cell_format=format2) |
到此這篇關(guān)于如何使用Pandas的ExcelWriter進(jìn)行excel操作的文章就介紹到這了



評(píng)論