python處理excel(二):寫


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

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

新建一個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 #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效果如下。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM