在Python操作Excel 的模塊有 xlrd、xlwt、xlutils等。
xlrd:讀取Excel文件數據
xlwt:寫入Excel 數據,缺點是Excel格式無法復用,為了方便用戶,寫入的話,比較推薦xlutils模塊,它可以可復制原excel格式
1 復制代碼 2 #coding=utf-8 3 import xlrd,xlwt 4 from xlutils.copy import copy 5 6 #讀取文件 7 read_file = xlrd.open_workbook(file_path,formatting_info=True) 8 #參數注釋: 9 #file_path:文件路徑,包含文件的全名稱 10 #formatting_info=True:保留Excel的原格式 11 12 #將文件復制到內存 13 write_data = copy(read_file) 14 15 #讀取復制后文件的sheet1 16 write_save = write_data.get_sheet(0) 17 18 #寫入數據 19 write_save.write(x,y,value) 20 #參數注釋: 21 #x,y:寫入目標格的位置坐標 22 #value:寫入數據 23 24 #保存寫入數據后的文件到原文件路徑 25 write_data.save(self.file_path)
樣式:
1 #coding:utf-8 2 import os 3 import time 4 import xlwt 5 6 filename="test_xlwt.xls" 7 if os.path.exists(filename): 8 os.remove(filename) 9 def set_color(color,bold): 10 style=xlwt.XFStyle() 11 font=xlwt.Font() 12 font.colour_index=color 13 font.bold = bold 14 style.font=font 15 return style 16 title_style=set_color(0x06,True) 17 xls=xlwt.Workbook() 18 shet1=xls.add_sheet("test_sheet") 19 shet1.write(0,0,"test",set_color(0x02,True)) #紅色 20 shet1.write(0,1,"test",set_color(0x05,False)) #黃色 21 shet1.write(0,2,u"你好",set_color(0x00,True)) #黑色加粗 22 shet1.write(0,3,u"你好",set_color(0x00,False)) #黑色不加粗 23 shet1.write(0,4,u"你好",title_style) #黑色加粗 24 xls.save("test_xlwt.xls")
1 import xlwt 2 from datetime import datetime 3 4 # 設置樣式 字體name Times New Roman 字體顏色為紅色 數字格式為:#,##0.00 5 style0 = xlwt.easyxf('font: name Times New Roman, color-index red, bold on', 6 num_format_str='#,##0.00') 7 8 # 設置樣式 日期格式為D-MMM-YY 9 style1 = xlwt.easyxf(num_format_str='D-MMM-YY') 10 11 # 新建工作簿 12 wb = xlwt.Workbook() 13 14 # 新建工作表 15 ws = wb.add_sheet('A Test Sheet') 16 17 # 向某行某列寫入數據 18 ws.write(0, 0, 1234.56, style0) 19 ws.write(1, 0, datetime.now(), style1) 20 ws.write(2, 0, 1) 21 ws.write(2, 1, 1) 22 ws.write(2, 2, xlwt.Formula("A3+B3")) 23 24 # 保存工作表 25 wb.save('1.xls')