最近小編在處理各類.xlsx表格的數據處理和計算的工做,目前python用於操做表格的模塊有不少,功能各有千秋。本文主要講的是xlwt用於寫,xlrt用於讀。html
簡單的寫入功能可用xlwt
模塊,寫入功能的難點在於寫入合併的單元格。單元格的下標都是從0開始。python
xlwt官方API:https://xlwt.readthedocs.io/en/latest/api.htmlapi
安裝:app
pip install xlwt
wk=xlwt.Workbook()
sheet1 = wk.add_sheet("數據", cell_overwrite_ok=True)
sheet1.write(2 , 1, "liebao") # 參數一:行下標 # 參數二:列下標 # 參數三:寫入的內容
# 列合併:寫入第2行,第2~5列 sheet1.write_merge(1, 1, 1, 4, "列合併") # 行合併:寫入第1~3行,第3列 sheet1.write_merge(0, 2, 2, 2, "行合併") # 參數一:開始的行下標 # 參數二:結束的行下標(包含) # 參數三:開始的列下標 # 參數四:結束的列下標(包含) # 參數五:寫入的內容
wk.save(file_name) # 參數一:保存的表格文件名或者流
可是咱們的單元格怎麼設置樣式呢?通常的單元格都會調整樣式,如合併居中、設置字體大小、背景色等等?字體
如何寫入公式?excel
如實現下面的code
{orm
def xlwt_excel(): ''' 表格寫入 :return: ''' # 得到可寫入的workbook對象 wk = xlwt.Workbook() # 增長一個sheet 而且單元格可重寫 sheet1 = wk.add_sheet(sheet_name, cell_overwrite_ok=True) # 合併的行:寫入合併的第1、二行 for i in range(0, len(row0_2)): sheet1.write_merge(0, 1, i, i, row0_2[i], get_style()) # 寫入單個最後一列的第1、二行:分開的兩行消耗(元) 折前 sheet1.write(0, len(row0_2), simple_end_col[0], get_style()) sheet1.write(1, len(row0_2), simple_end_col[1], get_style()) # 合併的行:寫第一列 sheet1.write_merge(2, len(liebao_accounts) + 1, 0, 0, colum0[0], get_style()) sheet1.write_merge(2 + len(liebao_accounts), len(liebao_accounts) + len(wifi_accounts) + 1, 0, 0, colum0[1], get_style()) # 寫入單個單元格:寫獵豹數據: for index in range(0, len(liebao_accounts)): sheet1.write(2 + index, 1, liebao_accounts[index]['app'], get_style(True)) sheet1.write(2 + index, 2, liebao_accounts[index]['system'], get_style(True)) sheet1.write(2 + index, 3, liebao_accounts[index]['account'], get_style(True)) sheet1.write(2 + index, 4, float(liebao_accounts[index]['spend']), get_style(True)) # 寫入單個單元格:寫入wifi數據 for index in range(0, len(wifi_accounts)): sheet1.write(2 + len(liebao_accounts) + index, 1, wifi_accounts[index]['app'], get_style(True)) sheet1.write(2 + len(liebao_accounts) + index, 2, wifi_accounts[index]['system'], get_style(True)) sheet1.write(2 + len(liebao_accounts) + index, 3, wifi_accounts[index]['account'], get_style(True)) sheet1.write(2 + len(liebao_accounts) + index, 4, float(wifi_accounts[index]['spend']), get_style(True)) # 寫入數字格式化 sheet1.write_merge(2 + len(liebao_accounts) + len(wifi_accounts), 2 + len(liebao_accounts) + len(wifi_accounts), 0, 1, datetime.now(), get_style(num_format=True)) # 寫入合併列:合計 sheet1.write_merge(2 + len(liebao_accounts) + len(wifi_accounts), 2 + len(liebao_accounts) + len(wifi_accounts), 2, 3, "合計", get_style()) # 寫入公式:求和消耗總和 sheet1.write(2 + len(liebao_accounts) + len(wifi_accounts), 4, xlwt.Formula("SUM(E3:E%d)" % (3 + len(liebao_accounts) + len(wifi_accounts) - 1)), get_style()) # 寫入超連接 sheet1.write_merge(3 + len(liebao_accounts) + len(wifi_accounts), 3 + len(liebao_accounts) + len(wifi_accounts), 0, 4, xlwt.Formula('HYPERLINK("https://sunflowercoder.com/";"更多好文 點擊查看個人博客")'), get_style(bold=True)) # 修改列寬度 for i in range(0, len(row0_2) + 1): sheet1.col(i).width = 150 * 30 # 定義列寬 sheet1.col(0).width = 50 * 30 # 定義列寬 sheet1.col(2).width = 200 * 30 # 定義列寬 # 保存到文件 wk.save(file_name) def get_style(simple_ceil=False, num_format=False, bold=False): ''' 設置表格樣式 :param simple_ceil: 是否爲 普通單元格,默認爲非普通單元格 :param num_format: 是否爲須要格式化的數字單元格 :param bold: 是否須要加粗 :return: ''' style = xlwt.XFStyle() if not simple_ceil: # 字體 font = xlwt.Font() font.name = "宋體" font.bold = bold font.underline = False font.italic = False font.colour_index = 0 font.height = 200 # 200爲10號字體 style.font = font # 單元格居中 align = xlwt.Alignment() align.horz = xlwt.Alignment.HORZ_CENTER # 水平方向 align.vert = xlwt.Alignment.VERT_CENTER # 豎直方向 style.alignment = align # 背景色 pattern = xlwt.Pattern() pattern.pattern = xlwt.Pattern.SOLID_PATTERN pattern.pattern_fore_colour = xlwt.Style.colour_map['pale_blue'] # 設置單元格背景色爲黃色 style.pattern = pattern # 邊框 border = xlwt.Borders() # 給單元格加框線 border.left = xlwt.Borders.THIN # 左 border.top = xlwt.Borders.THIN # 上 border.right = xlwt.Borders.THIN # 右 border.bottom = xlwt.Borders.THIN # 下 border.left_colour = 0x40 # 邊框線顏色 border.right_colour = 0x40 border.top_colour = 0x40 border.bottom_colour = 0x40 style.borders = border # 數字格式化 if num_format: style.num_format_str = 'M/D/YY' # 選項: D-MMM-YY, D-MMM-YY, D-MMM, MMM-YY, h:mm, h:mm:ss, h:mm, h:mm:ss, M/D/YY h:mm, mm:ss, [h]:mm:ss, mm:ss.0 return style
讀取比較麻煩的是合併單元格的內容,Python讀取Excel中單元格的內容返回的有5種類型,ctype分別爲 : 0 empty,1 string,2 number, 3 date,4 boolean,5 errorhtm
xlrd官方API:https://xlrd.readthedocs.io/en/latest/api.html#module-xlrd對象
安裝:pip install xlrd
讀取示例:
def xlrd_excel(): ''' 表格讀取 :return: ''' # 打開文件 wb = xlrd.open_workbook(filename=file_name, formatting_info=True) # 獲取全部表格名字 print("全部的表格名:", wb.sheet_names()) # 經過索引獲取表格 sheet1 = wb.sheet_by_index(0) # 經過名字獲取表格 # sheet2 = wb.sheet_by_name(sheet_name) # 輸出表格的名字,行數和列數 print("第一個表格名:", sheet1.name, " 行數:", sheet1.nrows, " 列數:", sheet1.ncols) # 獲取行、列的內容 rows = sheet1.row_values(0) # 獲取第一行的內容 cols = sheet1.col_values(0) # 獲取第一列內容 print(rows) print(cols) # 獲取單元格內容 三種方式 print(sheet1.cell(0, 4).value) print(sheet1.cell_value(0, 4)) print(sheet1.row(0)[4].value) # 輸出合併表格的內容:注意 xlrd.open_workbook()時,必須formatting_info=True,不然merged_cells返回空 merged_cells = sheet1.merged_cells print("合併的單元格:", merged_cells) for item in merged_cells: # 合併的單元格爲元組形式 如(12, 13, 0, 2) 爲(開始的行標,結束的行標,開始的列標,結束的列標) 取值爲(開始的行標,開始的列標)便可 print("合併的單元格", item, "值爲:", sheet1.cell_value(item[0], item[2])) # Python讀取Excel中單元格的內容返回的有5種類型,ctype分別爲 : 0 empty,1 string,2 number, 3 date,4 boolean,5 error # 輸出日期格式 if sheet1.cell_type(12, 0) == 3: date_value = xlrd.xldate_as_tuple(sheet1.cell_value(12, 0), wb.datemode) print("日期爲:", date_value, ) print("日期爲(格式爲2019-09-17):", date(*date_value[:3])) print("日期爲(格式爲2019/09/17):", date(*date_value[:3]).strftime('%Y/%m/%d'))
xlwt
最大的弊端就是不能修改表格只能新增,修改的方法,小編會在後面的文章闡述。
須要示例代碼,點擊原文連接
💡 更多好文歡迎關注個人公衆號~