標籤:工作 str ksh name 匯入 line deb python utils
讀excel
1、匯入模組
import xlrd
2、開啟Excel檔案讀取資料
data = xlrd.open_workbook(‘excel.xls‘)
3、擷取一個工作表
① table = data.sheets()[0] #通過索引順序擷取
② table = data.sheet_by_index(0) #通過索引順序擷取
③ table = data.sheet_by_name(u‘Sheet1‘)#通過名稱擷取
4、擷取整行和整列的值(返回數組)
table.row_values(i)
table.col_values(i)
5、擷取行數和列數
table.nrowstable.ncols 6、擷取儲存格
table.cell(0,0).valuetable.cell(2,3).value
寫excel
1、匯入模組
import xlwt
2、建立workbook(其實就是excel,後來儲存一下就行)
workbook = xlwt.Workbook(encoding = ‘ascii‘)
3、建立表
worksheet = workbook.add_sheet(‘My Worksheet‘)
4、往儲存格內寫入內容
worksheet.write(0, 0, label = ‘Row 0, Column 0 Value‘)
5、儲存
workbook.save(‘Excel_Workbook.xls‘)
向已存在的excel中寫入資料
from xlrd import open_workbookfrom xlutils.copy import copy rb = open_workbook(‘m:\\1.xls‘) #通過sheet_by_index()擷取的sheet沒有write()方法rs = rb.sheet_by_index(0) wb = copy(rb) #通過get_sheet()擷取的sheet有write()方法ws = wb.get_sheet(0)ws.write(0, 0, ‘changed!‘) wb.save(‘m:\\1.xls‘) |
python操作excel