Python3 讀、寫Excel文件

首先,簡單介紹一下EXECL中工做簿和工做表的區別:html

工做簿的英文是BOOK(WORKBOOK),工做表的英文是SHEET(WORKSHEET)。python

  • 一個工做簿就是一個獨立的文件
  • 一個工做簿裏面能夠有1個或者多個工做表
  • 工做簿是工做表的集合

1:使用python實現對Excel文件的讀寫,首先須要安裝專用的模塊(能夠本身編寫)xlrd,xlwt模塊app

2:讀取excel數據(注意事項:sheet編號,行號,列號都是從索引0開始)函數

 1 import xlrd
 2 
 3 # 設置路徑
 4 path = 'E:/input.xlsx'
 5 # 打開execl
 6 workbook = xlrd.open_workbook(path)
 7 
 8 # 輸出Excel文件中全部sheet的名字
 9 print(workbook.sheet_names())
10 
11 # 根據sheet索引或者名稱獲取sheet內容
12 Data_sheet = workbook.sheets()[0]  # 經過索引獲取
13 # Data_sheet = workbook.sheet_by_index(0)  # 經過索引獲取
14 # Data_sheet = workbook.sheet_by_name(u'名稱')  # 經過名稱獲取
15 
16 
17 print(Data_sheet.name)  # 獲取sheet名稱
18 rowNum = Data_sheet.nrows  # sheet行數
19 colNum = Data_sheet.ncols  # sheet列數
20 
21 # 獲取全部單元格的內容
22 list = []
23 for i in range(rowNum):
24     rowlist = []
25     for j in range(colNum):
26         rowlist.append(Data_sheet.cell_value(i, j))
27     list.append(rowlist)
28 # 輸出全部單元格的內容
29 for i in range(rowNum):
30     for j in range(colNum):
31         print(list[i][j], '\t\t', end="")
32     print()
33 
34 # 獲取整行和整列的值(列表)
35 rows = Data_sheet.row_values(0)  # 獲取第一行內容
36 cols = Data_sheet.col_values(1)  # 獲取第二列內容
37 # print (rows)
38 # print (cols)
39 
40 # 獲取單元格內容
41 cell_A1 = Data_sheet.cell(0, 0).value
42 cell_B1 = Data_sheet.row(0)[1].value  # 使用行索引
43 cell_C1 = Data_sheet.cell(0, 2).value
44 cell_D2 = Data_sheet.col(3)[1].value  # 使用列索引
45 print(cell_A1, cell_B1, cell_C1, cell_D2)
46 
47 # 獲取單元格內容的數據類型
48 # ctype:0 empty,1 string, 2 number, 3 date, 4 boolean, 5 error
49 print('cell(0,0)數據類型:', Data_sheet.cell(0, 0).ctype)
50 print('cell(1,0)數據類型:', Data_sheet.cell(1, 0).ctype)
51 print('cell(1,1)數據類型:', Data_sheet.cell(1, 1).ctype)
52 print('cell(1,2)數據類型:', Data_sheet.cell(1, 2).ctype)
53 
54 # 獲取單元格內容爲日期的數據
55 date_value = xlrd.xldate_as_tuple(Data_sheet.cell_value(1,0),workbook.datemode)
56 print(type(date_value), date_value)
57 print('%d:%d:%d' % (date_value[0:3]))

 

 3:建立excel並寫入數據測試

import xlwt


def set_style(name, height, bold=False):
    style = xlwt.XFStyle()   # 初始化樣式
    font = xlwt.Font()       # 爲樣式建立字體
    font.name = name
    font.bold = bold
    font.color_index = 4
    font.height = height

    style.font = font
    return style


def write_excel(path):
    # 建立工做簿
    workbook = xlwt.Workbook(encoding='utf-8')
    # 建立sheet
    data_sheet = workbook.add_sheet('demo')
    row0 = [u'字段名稱', u'大體時段', 'CRNTI', 'CELL-ID']
    row1 = [u'測試', '15:50:33-15:52:14', 22706, 4190202]
    # 生成第一行和第二行
    for i in range(len(row0)):
        data_sheet.write(0, i, row0[i], set_style('Times New Roman', 220, True))
        data_sheet.write(1, i, row1[i], set_style('Times New Roman', 220, True))

    # 保存文件
    # workbook.save('demo.xls')
    workbook.save(path)


if __name__ == '__main__':
    # 設置路徑
    path = 'E:/demo.xls'
    write_excel(path)
    print(u'建立demo.xls文件成功')

 

再看一個例子:字體

轉載:Ryan in C++spa

基本的write函數接口很簡單:3d

  • 新建一個excel文件:                                                 file = xlwt.Workbook() (注意這裏的Workbook首字母是大寫)
  • 新建一個sheet:                                                        table = file.add_sheet('sheet_name')
  • 寫入數據table.write(行,列,value):                            table.write(0,0,'test')
  • 若是是寫入中文,則要用u'漢字'的形式。好比:       table.write(0,0, u'漢字')
  • 合併單元格:                                                             table.write_merge(x, x + m, y, y + n, string, style)
  • x表示行,y表示列,m表示跨行個數,n表示跨列個數,string表示要寫入的單元格內容,style表示單元格樣式
 1 """
 2 設置單元格樣式
 3 """
 4 import xlwt
 5 
 6 
 7 def set_style(font_name, font_height, bold=False):
 8     style = xlwt.XFStyle()  # 初始化樣式
 9 
10     font = xlwt.Font()  # 爲樣式建立字體
11     font.name = font_name  # 'Times New Roman'
12     font.bold = bold
13     font.color_index = 4
14     font.height = font_height
15 
16     borders = xlwt.Borders()
17     borders.left = 6
18     borders.right = 6
19     borders.top = 6
20     borders.bottom = 6
21 
22     style.font = font
23     style.borders = borders
24 
25     return style
26 
27 
28 # 寫excel
29 def write_excel(output_path):
30     f = xlwt.Workbook() # 建立工做簿
31     '''
32     建立第一個sheet:
33         sheet1
34     '''
35     sheet1 = f.add_sheet(u'sheet1',cell_overwrite_ok=True)  # 建立sheet
36     row0 = [u'業務',u'狀態',u'北京',u'上海',u'廣州',u'深圳',u'狀態小計',u'合計']
37     column0 = [u'機票',u'船票',u'火車票',u'汽車票',u'其它']
38     status = [u'預訂',u'出票',u'退票',u'業務小計']
39     # 生成第一行
40     for i in range(0, len(row0)):
41         sheet1.write(0, i, row0[i], set_style('Times New Roman', 220, True))
42 
43     # 生成第一列和最後一列(合併4行)
44     i, j = 1, 0
45     while i < 4*len(column0) and j < len(column0):
46         sheet1.write_merge(i, i+3, 0, 0, column0[j], set_style('Arial', 220, True))  # 第一列
47         sheet1.write_merge(i, i+3, 7, 7)  # 最後一列"合計"
48         i += 4
49         j += 1
50 
51     sheet1.write_merge(21,21,0,1,u'合計',set_style('Times New Roman',220,True))
52 
53     # 生成第二列
54     i = 0
55     while i < 4*len(column0):
56         for j in range(0,len(status)):
57             sheet1.write(j+i+1, 1, status[j])
58         i += 4
59 
60     f.save(output_path)
61 
62 
63 if __name__ == '__main__':
64     write_excel('E:/demo.xls')  # 保存文件.這裏若是是.xlsx的話會打不開。

 

注意:若是對一個單元格重複操做,會引起error。因此在打開時加cell_overwrite_ok=True解決excel

table = file.add_sheet('sheet name',cell_overwrite_ok=True)

生成的demo.xls效果以下:code

相關文章
相關標籤/搜索