python讀寫(xiě)Excel
最近小編在處理各種.xlsx表格的數(shù)據(jù)處理和計(jì)算的工作,目前python用于操作表格的模塊有很多,功能各有千秋。本文主要講的是xlwt用于寫(xiě),xlrt用于讀。
表格寫(xiě)入
簡(jiǎn)單的寫(xiě)入功能可用
xlwt
模塊,寫(xiě)入功能的難點(diǎn)在于寫(xiě)入合并的單元格。
單元格的下標(biāo)都是從0開(kāi)始
。
xlwt官方API: https://xlwt.readthedocs.io/e...
安裝:
pip install xlwt
-
新建workbook:
wk=xlwt.Workbook()
-
新建sheet:
sheet1 = wk.add_sheet("數(shù)據(jù)", cell_overwrite_ok=True)
-
寫(xiě)入普通單元格:寫(xiě)入第3行,第2列
sheet1.write(2 , 1, "liebao") # 參數(shù)一:行下標(biāo) # 參數(shù)二:列下標(biāo) # 參數(shù)三:寫(xiě)入的內(nèi)容
-
寫(xiě)入合并的單元格:
# 列合并:寫(xiě)入第2行,第2~5列 sheet1.write_merge(1, 1, 1, 4, "列合并") # 行合并:寫(xiě)入第1~3行,第3列 sheet1.write_merge(0, 2, 2, 2, "行合并") # 參數(shù)一:開(kāi)始的行下標(biāo) # 參數(shù)二:結(jié)束的行下標(biāo)(包含) # 參數(shù)三:開(kāi)始的列下標(biāo) # 參數(shù)四:結(jié)束的列下標(biāo)(包含) # 參數(shù)五:寫(xiě)入的內(nèi)容
-
保存至表格文件
wk.save(file_name) # 參數(shù)一:保存的表格文件名或者流
但是我們的單元格怎么設(shè)置樣式呢?一般的單元格都會(huì)調(diào)整樣式,如合并居中、設(shè)置字體大小、背景色等等?
如何寫(xiě)入公式?
如實(shí)現(xiàn)下面的
def xlwt_excel():
'''
表格寫(xiě)入
:return:
'''
# 獲得可寫(xiě)入的workbook對(duì)象
wk = xlwt.Workbook()
# 增加一個(gè)sheet 并且單元格可重寫(xiě)
sheet1 = wk.add_sheet(sheet_name, cell_overwrite_ok=True)
# 合并的行:寫(xiě)入合并的第一、二行
for i in range(0, len(row0_2)):
sheet1.write_merge(0, 1, i, i, row0_2[i], get_style())
# 寫(xiě)入單個(gè)最后一列的第一、二行:分開(kāi)的兩行消耗(元) 折前
sheet1.write(0, len(row0_2), simple_end_col[0], get_style())
sheet1.write(1, len(row0_2), simple_end_col[1], get_style())
# 合并的行:寫(xiě)第一列
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())
# 寫(xiě)入單個(gè)單元格:寫(xiě)獵豹數(shù)據(jù):
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))
# 寫(xiě)入單個(gè)單元格:寫(xiě)入wifi數(shù)據(jù)
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))
# 寫(xiě)入數(shù)字格式化
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))
# 寫(xiě)入合并列:合計(jì)
sheet1.write_merge(2 + len(liebao_accounts) + len(wifi_accounts), 2 + len(liebao_accounts) + len(wifi_accounts), 2,
3, "合計(jì)", get_style())
# 寫(xiě)入公式:求和消耗總和
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())
# 寫(xiě)入超鏈接
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/";"更多好文 點(diǎn)擊查看我的博客")'),
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):
'''
設(shè)置表格樣式
:param simple_ceil: 是否為 普通單元格,默認(rèn)為非普通單元格
:param num_format: 是否為需要格式化的數(shù)字單元格
: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號(hào)字體
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'] # 設(shè)置單元格背景色為黃色
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
# 數(shù)字格式化
if num_format:
style.num_format_str = 'M/D/YY' # 選項(xiàng): 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
表格讀取
讀取比較麻煩的是合并單元格的內(nèi)容,Python讀取Excel中單元格的內(nèi)容返回的有5種類(lèi)型,ctype分別為 : 0 empty,1 string,2 number, 3 date,4 boolean,5 error
xlrd官方API: https://xlrd.readthedocs.io/e...
安裝:
pip install xlrd
讀取示例:
def xlrd_excel():
'''
表格讀取
:return:
'''
# 打開(kāi)文件
wb = xlrd.open_workbook(filename=file_name, formatting_info=True)
# 獲取所有表格名字
print("所有的表格名:", wb.sheet_names())
# 通過(guò)索引獲取表格
sheet1 = wb.sheet_by_index(0)
# 通過(guò)名字獲取表格
# sheet2 = wb.sheet_by_name(sheet_name)
# 輸出表格的名字,行數(shù)和列數(shù)
print("第一個(gè)表格名:", sheet1.name, " 行數(shù):", sheet1.nrows, " 列數(shù):", sheet1.ncols)
# 獲取行、列的內(nèi)容
rows = sheet1.row_values(0) # 獲取第一行的內(nèi)容
cols = sheet1.col_values(0) # 獲取第一列內(nèi)容
print(rows)
print(cols)
# 獲取單元格內(nèi)容 三種方式
print(sheet1.cell(0, 4).value)
print(sheet1.cell_value(0, 4))
print(sheet1.row(0)[4].value)
# 輸出合并表格的內(nèi)容:注意 xlrd.open_workbook()時(shí),必須formatting_info=True,否則merged_cells返回空
merged_cells = sheet1.merged_cells
print("合并的單元格:", merged_cells)
for item in merged_cells:
# 合并的單元格為元組形式 如(12, 13, 0, 2) 為(開(kāi)始的行標(biāo),結(jié)束的行標(biāo),開(kāi)始的列標(biāo),結(jié)束的列標(biāo)) 取值為(開(kāi)始的行標(biāo),開(kāi)始的列標(biāo))即可
print("合并的單元格", item, "值為:", sheet1.cell_value(item[0], item[2]))
# Python讀取Excel中單元格的內(nèi)容返回的有5種類(lèi)型,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
最大的弊端就是不能修改表格只能新增,修改的方法,小編會(huì)在后面的文章闡述。
需要示例代碼,點(diǎn)擊原文鏈接
更多好文歡迎關(guān)注我的公眾號(hào)~
更多文章、技術(shù)交流、商務(wù)合作、聯(lián)系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號(hào)聯(lián)系: 360901061
您的支持是博主寫(xiě)作最大的動(dòng)力,如果您喜歡我的文章,感覺(jué)我的文章對(duì)您有幫助,請(qǐng)用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點(diǎn)擊下面給點(diǎn)支持吧,站長(zhǎng)非常感激您!手機(jī)微信長(zhǎng)按不能支付解決辦法:請(qǐng)將微信支付二維碼保存到相冊(cè),切換到微信,然后點(diǎn)擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對(duì)您有幫助就好】元
