本文實(shí)例講述了Python使用xlwt模塊操作Excel的方法。分享給大家供大家參考,具體如下:
部分摘自官網(wǎng)文檔.
該模塊安裝很簡(jiǎn)單
$ pip install xlwt
先來(lái)個(gè)簡(jiǎn)單的例子:
#!/usr/bin/python#coding=utf-8# ==============================================================================## Filename: demo.py# Description: excel operat# Created: Tue Apr 25 17:10:33 CST 2017# Author: Yur## ==============================================================================import xlwt# 創(chuàng)建一個(gè)workbook 設(shè)置編碼workbook = xlwt.Workbook(encoding = 'utf-8')# 創(chuàng)建一個(gè)worksheetworksheet = workbook.add_sheet('My Worksheet')# 寫(xiě)入excel# 參數(shù)對(duì)應(yīng) 行, 列, 值worksheet.write(1,0, label = 'this is test')# 保存workbook.save('Excel_test.xls')運(yùn)行后 會(huì)在當(dāng)前目錄生成一個(gè)Excel_test.xls
官方例子:

運(yùn)行這個(gè)例子的時(shí)候 報(bào)錯(cuò)

自己又寫(xiě)了一個(gè):
#!/usr/bin/python#coding=utf-8# ==============================================================================## Filename: style.py# Description: style# Created: Thu Apr 27 15:07:53 CST 2017# Author: Yur## ==============================================================================import xlwtworkbook = xlwt.Workbook(encoding = 'ascii')worksheet = workbook.add_sheet('My Worksheet')style = xlwt.XFStyle() # 初始化樣式font = xlwt.Font() # 為樣式創(chuàng)建字體font.name = 'Times New Roman'font.bold = True # 黑體font.underline = True # 下劃線font.italic = True # 斜體字style.font = font # 設(shè)定樣式worksheet.write(0, 0, 'Unformatted value') # 不帶樣式的寫(xiě)入worksheet.write(1, 0, 'Formatted value', style) # 帶樣式的寫(xiě)入workbook.save('formatting.xls') # 保存文件效果:

設(shè)置單元格寬度:
import xlwtworkbook = xlwt.Workbook()worksheet = workbook.add_sheet('My Sheet')worksheet.write(0, 0,'My Cell Contents')# 設(shè)置單元格寬度worksheet.col(0).width = 3333workbook.save('cell_width.xls')輸入一個(gè)日期到單元格:
import xlwtimport datetimeworkbook = xlwt.Workbook()worksheet = workbook.add_sheet('My Sheet')style = xlwt.XFStyle()style.num_format_str = 'M/D/YY' # Other options: D-MMM-YY, D-MMM, MMM-YY, h:mm, h:mm:ss, h:mm, h:mm:ss, M/D/YY h:mm, mm:ss, [h]:mm:ss, mm:ss.0worksheet.write(0, 0, datetime.datetime.now(), style)workbook.save('Excel_Workbook.xls')向單元格添加一個(gè)公式:
import xlwtworkbook = xlwt.Workbook()worksheet = workbook.add_sheet('My Sheet')worksheet.write(0, 0, 5) # Outputs 5worksheet.write(0, 1, 2) # Outputs 2worksheet.write(1, 0, xlwt.Formula('A1*B1')) # Should output "10" (A1[5] * A2[2])worksheet.write(1, 1, xlwt.Formula('SUM(A1,B1)')) # Should output "7" (A1[5] + A2[2])workbook.save('Excel_Workbook.xls')
新聞熱點(diǎn)
疑難解答
圖片精選