Excel表格是微軟開發(fā)的格式,在Linux上操作比較復雜
python操作xlsx文件常用的包有三個:
-
xlrd:xlsx reader,只能讀數(shù)據(jù) -
xlwt::xlsx writer,只能從前往后按順序?qū)憯?shù)據(jù) -
xlsxWriter:可以寫數(shù)據(jù)和樣式
此外還有結(jié)合了xlrd和xlwt的xlutils包
這里記錄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)