轉:https://www.cnblogs.com/ultimateWorld/p/8309197.html
Python語法簡潔清晰,作為工作中常用的開發語言還是很強大的(廢話)。
python關於Excel的操作提供了xlwt和xlrd兩個的包作為針對Excel通用操作的支持,跨平台(Mac、Windows均可)。
xlrdxlrd目前支持讀寫xlsx(2007版)與xls(2003版),簡單的說明如下:
import xlrd
def open_excel(file='test.xls'):
try:
data = xlrd.open_workbook(file)
# 通過索引獲取工作表
sheet1 = data.sheets()[0]
# 通過名稱獲取工作表
sheet1 = data.sheet_by_name(u'sheet1')
# 獲取table對象,根據table進行該工作表相關數據的讀取
# 獲取行列
row = sheet1.nrows
col = sheet1.ncols
# 獲取單元格的值
cell_value = sheet1.cell(0, 1).value
# 行列表數據
for i in range(row):
print sheet1.row_values(i)
# 數據寫入
# 單元格類型 0 empty,1 string, 2 number, 3 datetime, 4 boolean, 5 error
# xf 擴展格式化
xf = 0
row_num = 1
col_num = 1
cell_type = 1
sheet1.put_cell(row_num, col_num, cell_type, u'hello word', xf)
return data
except Exception, e:
print str(e)
xlwt則支持寫出2003版xls的包,具體操作如示例如下:
import xlwt
def write_excel2():
# 設置通用樣式變量
style_header = xlwt.easyxf(u'font: name 微軟雅黑, color-index black, bold on,height 240')
workbook = xlwt.Workbook()
worksheet = workbook.add_sheet(u'sheet1')
# 設置第一列到單元格的寬度
worksheet.col(0).width = 256 * 35
# 設置該工作表單元格的寬度
c = 1
while c < 300:
worksheet.col(c).width = 256 * 20
c += 1
col = 0
# 循環設置表頭值
header = [u'姓名', u'性別', u'年齡']
for h in header:
worksheet.write(0, col, h, style_header)
col += 1
# 保存到本地目錄,mac上后綴xlsx會報錯,xls正常。
workbook.save('test.xls')
xlsxwriter支持2007版的寫出
import xlsxwriter #導入模塊
workbook = xlsxwriter.Workbook('new_excel.xlsx') #新建excel表
worksheet = workbook.add_worksheet('sheet1') #新建sheet(sheet的名稱為"sheet1")
headings = ['Number','testA','testB'] #設置表頭
data = [
['2017-9-1','2017-9-2','2017-9-3','2017-9-4','2017-9-5','2017-9-6'],
[10,40,50,20,10,50],
[30,60,70,50,40,30],
] #自己造的數據
worksheet.write_row('A1',headings)
worksheet.write_column('A2',data[0])
worksheet.write_column('B2',data[1])
worksheet.write_column('C2',data[2]) #將數據插入到表格中
workbook.close() #將excel文件保存關閉,如果沒有這一行運行代碼會報錯
