xlsxWriter重構(gòu)Excel表格

Excel表格是微軟開發(fā)的格式,在Linux上操作比較復雜
python操作xlsx文件常用的包有三個:

  • xlrd:xlsx reader,只能讀數(shù)據(jù)
  • xlwt::xlsx writer,只能從前往后按順序?qū)憯?shù)據(jù)
  • xlsxWriter:可以寫數(shù)據(jù)和樣式

此外還有結(jié)合了xlrdxlwtxlutils
這里記錄xlsxWriter
官方文檔


新建項目

導入時注意全小寫:

import xlsxwriter

打開和關(guān)閉:xlwt在最后調(diào)用.save(fp)方法時傳入保存路徑,而xlsxWriter在新建項目(Workbook)時就指明輸出文件路徑,最后使用.close()關(guān)閉:

wb = xlsxwriter.Workbook(fp)
...
wb.close()

新建工作表(Worksheet):

ws = wb.add_worksheet('工作表的名字')

常用操作


設置單元格樣式

先定義好表格樣式,進行整體布局
使用 format0 = wb.add_format({...}) 添加樣式

字體大小、顏色、加粗

'font_size': 15 # 注意單位是磅
'color': 'red' # 字體顏色
'bold': True # 是否加粗

水平、垂直方向文本對齊

'align': 'center' # 水平方向居中,默認左對齊
'valign': 'vcenter' # 垂直方向居中

列寬和行高

一列/一行所有單元格的列寬/行高是相同的,因此列寬/行高應該以列/行為單位進行設置

列設置

ws.set_column(self, firstcol, lastcol, width=None, cell_format=None, options={}) # 這里列寬單位我還沒弄明白??

行設置

ws.set_row(self, row, height=None, cell_format=None, options={}) # 這里的單位是磅

往單元格里寫值

寫入普通字符串write_string(self, row, col, string, cell_format=None)

寫入日期write_datetime(self, row, col, date, cell_format=None)

date是一個datetime.datetime對象

  • datetime.datetime對象可以通過datetime.datetime(int_year, int_month, int_day)創(chuàng)建
  • xlrd.xldate_as_tuple(float_number)可以將浮點數(shù)解析成y元組(Y, M, D, h, m, s)

cell_format應該指出日期的字符串顯示,畢竟datetime.datetime對象不可能被打印在屏幕上~

cell_format = wb.add_format({ELSE_FORMAT, 'num_format': 'yyyy-mm-dd'})

寫入其他類型

write_number(self, row, col, number, cell_format=None)

write_blank(self, row, col, blank, cell_format=None) # `blank`不管賦什么值都會被忽略

write_formula(self, row, col, formula, cell_format=None, value=0)

write_array_formula(self, first_row, first_col, last_row, last_col, formula, cell_format=None, value=0)

write_boolean(self, row, col, boolean, cell_format=None)

write_url(self, row, col, url, cell_format=None, string=None, tip=None)

合并單元格

merge_range(self, first_row, first_col, last_row, last_col, data, cell_format=None)

其他

數(shù)據(jù)有效性

列表驗證

ws.data_validation(self, first_row, first_col, last_row, last_col, {'validate': 'list', 'source': LIST_SELECT})

合并字典奇淫

c = dict(a, **b)
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關(guān)閱讀更多精彩內(nèi)容

  • 本例為設置密碼窗口 (1) If Application.InputBox(“請輸入密碼:”) = 1234 Th...
    浮浮塵塵閱讀 14,735評論 1 20
  • 小朋友最愛玩游戲,尤其2歲開始,游戲不再僅僅是游戲,更是她們探索與學習的有效方式。男孩最愛車,而我家女孩最愛過家家...
    Jane家的貓閱讀 305評論 0 0
  • 我小姑比父親小十歲,我記事起,小姑早已成家,有了兒子和女兒。每年過春節(jié)或暑假,都會聚在一起,大人們家長里短嘮嗑,我...
    玉妮閱讀 1,781評論 3 7
  • 小伙伴們,即時發(fā)布再多的美國appstore的公用賬號,還是無法保證它一直是可以使用的。 因此,自己擁有一個臺灣或...
    Levan_li閱讀 152,289評論 4 2
  • 今天下午,陽光明媚,經(jīng)過南山文化中心旁邊的廣場,心里想著今天寫什么呢? 抬頭一看,原來種著很多蔬菜的地還是只長著稀...
    悠悠心旅閱讀 599評論 0 0

友情鏈接更多精彩內(nèi)容