python excel 操做

在工做中常常碰到要導出excel或者將excel的數據導入數據庫,在用python處理excel的時候經常使用到xlrd和xlwt兩個庫來對excel進行讀取數據和寫入數據,讀取以下:python

import xlrd
workbook = xlrd.open_workbook(r'test.xlsx')
print workbook.sheet_names()
sheet2_name= workbook.sheet_names()[0]
print sheet2_name
sheet2 = workbook.sheet_by_name('Sheet1')
print sheet2.name,sheet2.nrows,sheet2.ncols
rows = sheet2.row_values(3)
print rows
nrows = sheet2.nrows
print nrows
for n in xrange(1,nrows):   
    cell_value1 = sheet2.row_values(n)  
    print cell_value1
    print cell_value1[0]
    print cell_value1[1]

上述代碼包含讀取excel各項數據,獲取用了多少行,經過for循環來獲取每行,每一個單元格的數據,若是隻是單純的獲取一個單元格的數據,能夠用這行 sheet2.cell(x,y).value (x爲行號,y爲列號) 直接獲取。數據庫

導出excel有多種方法,能夠經過xlwt或者xlrd來將數據寫入,以下:測試

import xlwt
style1 = xlwt.easyxf(num_format_str='D-MMM-YY')
wb = xlwt.Workbook()
ws = wb.add_sheet('adTest')
ws.write(0, 0, 1234.56)
ws.write(1, 0, '你好'.encode('GB18030')
ws.write(2, 0, 1)

也能夠經過csv庫來直接導出,以下(能夠用循環來進行多行的數據插入):編碼

response = HttpResponse(mimetype="text/csv",content_type="text/csv")  
name = time.strftime('%Y%m%d%H%M%S')
response['Content-Disposition'] = 'attachment; filename=%s.csv'%name  
writer = csv.writer(response)  
writer.writerow([u'序號'.encode('GB18030'),'表1'.encode('GB18030'),u'表2'.encode('GB18030')]) 
writer.writerow([xh,'測試'.encode('GB18030'),'測試'.encode('GB18030')) 
return response

除了上面直接按行寫到excel的,還能夠將數據按照顯示要求排列好,最後返回式時設置response.headers["Content-Disposition"] = "attachment; filename=data.csv"來返回csv。在導出中文時,若是直接導出中文會是亂碼,在測試了幾種編碼後以爲GB18030編碼對於excel導出中文適應性很好。excel

相關文章
相關標籤/搜索