python處理excel(二):寫

代碼參考自zhoujie。函數接口可參考該bloghtml

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

新建一個excel文件函數

file = xlwt.Workbook() (注意這裏的Workbook首字母是大寫)字體

新建一個sheetspa

table = file.add_sheet('sheet_name')excel

寫入數據table.write(行,列,value)code

table.write(0,0,'test')htm

若是是寫入中文,則要用u'漢字'的形式。好比blog

table.write(0,0, u'漢字')接口

合併單元格:

table.write_merge(x, x + m, y, y + n, string, style)

x表示行,y表示列,m表示跨行個數,n表示跨列個數,string表示要寫入的單元格內容,style表示單元格樣式。

 

 

 1 #coding=utf8
 2 '''
 3 設置單元格樣式
 4 '''
 5 import xlwt, xlrd
 6 
 7 def set_style(name,height,bold=False):
 8     style = xlwt.XFStyle()  # 初始化樣式
 9 
10     font = xlwt.Font()  # 爲樣式建立字體
11     font.name = name # 'Times New Roman'
12     font.bold = bold
13     font.color_index = 4
14     font.height = 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():
30     f = xlwt.Workbook() #建立工做簿
31 
32     '''
33     建立第一個sheet:
34         sheet1
35     '''
36     sheet1 = f.add_sheet(u'sheet1',cell_overwrite_ok=True) #建立sheet
37     row0 = [u'業務',u'狀態',u'北京',u'上海',u'廣州',u'深圳',u'狀態小計',u'合計']
38     column0 = [u'機票',u'船票',u'火車票',u'汽車票',u'其它']
39     status = [u'預訂',u'出票',u'退票',u'業務小計']
40 
41     #生成第一行
42     for i in range(0,len(row0)):
43         sheet1.write(0,i,row0[i],set_style('Times New Roman',220,True))
44 
45     #生成第一列和最後一列(合併4行)
46     i, j = 1, 0
47     while i < 4*len(column0) and j < len(column0):
48         sheet1.write_merge(i,i+3,0,0,column0[j],set_style('Arial',220,True)) #第一列
49         sheet1.write_merge(i,i+3,7,7) #最後一列"合計"
50         i += 4
51         j += 1
52 
53     sheet1.write_merge(21,21,0,1,u'合計',set_style('Times New Roman',220,True))
54 
55     #生成第二列
56     i = 0
57     while i < 4*len(column0):
58         for j in range(0,len(status)):
59             sheet1.write(j+i+1,1,status[j])
60         i += 4
61 
62     f.save('demo1.xls') #保存文件.這裏若是是.xlsx的話會打不開。
63 
64 if __name__ == '__main__':
65     #generate_workbook()
66     #read_excel()
67     write_excel()

注意:最終生成的文件若是是demo1.xlsx的話打不開,.xls就沒問題。

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

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

 

生成的demo1.xls效果以下。

相關文章
相關標籤/搜索