在python中操作excel
一、可使用的第三方庫
python中處理excel表格,常用的庫有xlrd(讀excel)表、xlwt(寫excel)表、openpyxl(可讀寫excel表)等。xlrd讀數據較大的excel表時效率高于openpyxl,所以我在寫腳本時就采用了xlrd和xlwt這兩個庫。 這些庫文件都沒有提供修改現有excel表格內容的功能。一般只能將原excel中的內容讀出、做完處理后,再寫入一個新的excel文件。
可以使用pip search excel 查看一下,可以看到更多的開發包。
二、常見問題
使用python處理excel表格時,發現兩個個比較難纏的問題:unicode編碼和excel中記錄的時間。
因為python的默認字符編碼都為unicode,所以打印從excel中讀出的中文或讀取中文名的excel表或sheet時,程序提示錯誤UnicodeEncodeError: ‘ascii’ codec can’t encode characters in position 0-2: ordinal not in range(128)。這是由于在windows中,中文使用了gb2312編碼方式,python將其當作unicode和ascii來解碼都不正確才報出的錯誤。使用VAR.encode(‘gb2312’)即可解決打印中文的問題。(很奇怪,有的時候雖然能打印出結果,但顯示的不是中文,而是一堆編碼。)若要從中文文件名的excel表中讀取數據,可在文件名前加‘u’表示將該中文文件名采用unicode編碼。
有excel中,時間和日期都使用浮點數表示。可看到,當‘2013年3月20日’所在單元格使用‘常規’格式表示后,內容變為‘41353’;當其單元格格式改變為日期后,內容又變為了‘2013年3月20日’。而使用xlrd讀出excel中的日期和時間后,得到是的一個浮點數。所以當向excel中寫入的日期和時間為一個浮點數也不要緊,只需將表格的表示方式改為日期和時間,即可得到正常的表示方式。excel中,用浮點數1表示1899年12月31日。
三、常用函數
以下主要介紹xlrd、xlwt、datetime中與日期相關的函數。
import xlrd import xlwt from datetimedef testXlrd(filename):book=xlrd.open_workbook(filename)sh=book.sheet_by_index(0)print "Worksheet name(s): ",book.sheet_names()[0]print 'book.nsheets',book.nsheetsprint 'sh.name:',sh.name,'sh.nrows:',sh.nrows,'sh.ncols:',sh.ncolsprint 'A1:',sh.cell_value(rowx=0,colx=1)#如果A3的內容為中文print 'A2:',sh.cell_value(0,2).encode('gb2312')def testXlwt(filename):book=xlwt.Workbook()sheet1=book.add_sheet('hello')book.add_sheet('word')sheet1.write(0,0,'hello')sheet1.write(0,1,'world')row1 = sheet1.row(1)row1.write(0,'A2')row1.write(1,'B2')sheet1.col(0).width = 10000sheet2 = book.get_sheet(1)sheet2.row(0).write(0,'Sheet 2 A1')sheet2.row(0).write(1,'Sheet 2 B1')sheet2.flush_row_data()sheet2.write(1,0,'Sheet 2 A3')sheet2.col(0).width = 5000sheet2.col(0).hidden = Truebook.save(filename)if __name__=='__main__':testXlrd(u'你好。xls')testXlwt('helloWord.xls')base=datetime.date(1899,12,31).toordinal()tmp=datetime.date(2013,07,16).toordinal()print datetime.date.fromordinal(tmp+base-1).weekday()總結
以上是生活随笔為你收集整理的在python中操作excel的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 美国监管机构申请法院暂停 Meta 收购
- 下一篇: websocket python爬虫_p