1. 程式人生 > 其它 >python3讀寫excel之xlrd和xlwt

python3讀寫excel之xlrd和xlwt

最新要處理excel檔案,於是整理了下python3中常用操作excel的包的用法

pip 用法

# 檢視已安裝
pip list
# 安裝包
pip install xlrd
# 安裝指定版本
pip install xlrd==1.2.0
# 解除安裝
pip uninstall xlrd

 xlrd

pip install xlrd

 xlrd 讀取 xls 檔案,讀取 xlsx 檔案出錯

import xlrd

workbook = xlrd.open_workbook('./source-files/info.xls', formatting_info=True)
print
(workbook.sheet_names()) # sheet = workbook.sheets()[0] #通過索引順序獲取sheet # sheet = workbook.sheet_by_index(0) #通過索引順序獲取sheet sheet = workbook.sheet_by_name('Sheet1') #通過名稱獲取sheet print(sheet.name) #sheet名稱 print(sheet.nrows, sheet.ncols) #行數、列數 print(sheet.row(rowx=0)) #整行 print(sheet.row_len(rowx=0)) #
返回該行的有效單元格長度 print(sheet.col(colx=0)) #整列 print(sheet.cell(rowx=0, colx=0)) #單元格 print(sheet.row_values(1)) #獲取整行的值 print(sheet.row_values(1, start_colx=0, end_colx=None)) #獲取某行的某列到另一列的值 print(sheet.col_values(1)) #獲取整列的值 print(sheet.col_values(0, start_rowx=1, end_rowx=2))#獲取某列的某行到另一行的值 print(sheet.cell_value(rowx=0, colx=0)) #
單元格的值 list_a = [] for i in range(0, sheet.nrows, 1): tmp = [] for j in range(0, sheet.ncols, 1): cell_type = sheet.cell_type(i, j) cell_value = sheet.cell_value(i, j) #處理日期格式 if cell_type == 3: tmp.append(xlrd.xldate_as_datetime( cell_value, workbook.datemode).strftime('%Y-%m-%d %H:%M:%S')) else: tmp.append(cell_value) list_a.append(tmp) print(list_a) #讀取合併單元格 print(sheet.merged_cells) for (row_start, row_end, col_start, col_end) in sheet.merged_cells: print(sheet.cell_value(rowx=row_start, colx=col_start))

 xlwt

pip install xlwt

 xlwt 生成 xls 檔案,生成的 xls 檔案最多能支援 65536 行、256列資料

import xlwt
import datetime
import os

workbook = xlwt.Workbook()
sheet = workbook.add_sheet('test')
style = xlwt.XFStyle()
# 字型
font = xlwt.Font()
font.name = 'Microsoft Yahei'
font.height = 20*12
font.bold = True
font.underline = True
font.italic = True
style.font = font
# 背景顏色
pattern_obj = xlwt.Pattern()
pattern_obj.pattern = xlwt.Pattern.SOLID_PATTERN
pattern_obj.pattern_fore_colour = 13
style.pattern = pattern_obj
# 邊框
borders = xlwt.Borders()
borders.left = xlwt.Borders.DASHED  # 虛線
borders.right = 1  # 實線
borders.left_colour = 0x000
borders.right_colour = 3
style.borders = borders
# 對齊
alignment_obj = xlwt.Alignment()
alignment_obj.horz = xlwt.Alignment.HORZ_CENTER
alignment_obj.vert = xlwt.Alignment.VERT_CENTER
style.alignment = alignment_obj

sheet.col(0).width = 2000

#日期格式
style1 = xlwt.XFStyle()
style1.num_format_str = "YYYY-M-D H:M:S"
for i in range(5):
    for j in range(4):
        sheet.write(i, j, i+j, style)
    #公式
    sheet.write(i, 4, xlwt.Formula("sum(A"+str(i+1)+":D"+str(i+1)+")"))
    #日期格式
    sheet.write(i, 5, datetime.datetime.now(), style1)
    #超連結
    sheet.write(i, 6, xlwt.Formula('HYPERLINK("https://www.baidu.com/";"Baidu")'))
    #合併單元格
    sheet.write_merge(i, i, 7, 8, 'value')

if os.path.exists('./gen-files/test.xls'):
    os.remove('./gen-files/test.xls')
workbook.save('./gen-files/test.xls')