在python中,對excel表格python
wlrd 讀取excel表中的數據
xlwt 建立一個全新的excel文件,而後對這個文件進行寫入內容以及保存。
xlutils 讀入一個excel文件,而後進行修改或追加,不能操做xlsx,只能操做xls。
讀excel要用到xlrd模塊
一、導入模塊編碼
import xlrd
二、打開excel文件,表格從0計數spa
import xlrd excel_calss = xlrd.open_workbook(r'C:\Users\joker\Desktop\ecs.xlsx') sheet = excel_calss.sheets()[0] # 經過索引順序獲取 sheet = excel_calss.sheet_by_index(0) # 經過索引順序獲取 sheet = excel_calss.sheet_by_name(u'Sheet1') # 經過名稱獲取
三、獲取表格行數和列數,行,列從0計數excel
import xlrd excel_calss = xlrd.open_workbook(r'C:\Users\joker\Desktop\ecs.xlsx') sheet = excel_calss.sheet_by_index(0) # 經過索引順序獲取 num_rows = sheet.nrows # 行數 int num_cols = sheet.ncols # 列數 int
四、獲取表格整行和整列的值,以列表形式返回,行,列從0計數code
sheet_row18 = sheet.row_values(18) # 獲取行得內容,列表形式 sheet_row19 = sheet.row_values(19) sheet_col1 = sheet.col_values(1) # 獲取列內容,列表形式 sheet_col2 = sheet.col_values(2)
五、獲取表格單元格數據對象
cell_A1 = sheet.cell(0,0).value # 指定單元格A1數據 cell_5145 = sheet.row(19)[1].value # 使用行索引肯定單元格數據 cell_5145 = sheet.col(1)[1].value # 使用列索引肯定單元格數據
一、導入模塊blog
import xlwt
二、建立workbook索引
workbook = xlwt.Workbook(encoding='utf-8', style_compression=0) encoding:設置字符編碼,通常要這樣設置:w = Workbook(encoding=’utf-8’),就能夠在excel中輸出中文了。默認是ascii style_compression:表示是否壓縮,不經常使用
三、建立一個sheet對象,一個sheet對象對應Excel文件中的一張表格utf-8
sheet = workbook.add_sheet('班級', cell_overwrite_ok=True) 其中的joker是這張表的名字,cell_overwrite_ok,表示是否能夠覆蓋單元格,實際上是Worksheet實例化的一個參數,默認值是False
四、向表中添加數據ci
sheet.write(0, 0, '名稱') # 其中的'0-行, 0-列'指定表中的單元,'名稱'是向該單元寫入的內容 sheet.write(0, 1, '年齡') username = 'joker' sheet.write(1, 0, username ) age = '18' sheet.write(1, 1, age)
五、保存
workbook.save(r'C:\Users\joker\Desktop\ecs.xls')
import xlrd import xlutils.copy excel_calss = xlrd.open_workbook(r'C:\Users\joker\Desktop\ecs.xls') excel_copy = xlutils.copy.copy(excel_calss) sheet=excel_copy.get_sheet(0) sheet.write(0,2,'性別') excel_copy.save(r'C:\Users\joker\Desktop\ecs.xls') # 追加前: # 姓名 年齡 # 追加後: # 姓名 年齡 性別
import csv import xlwt workbook = xlwt.Workbook() sheet2 = workbook.add_sheet("Sheet 2", cell_overwrite_ok=True) file = open(r'D:\label.csv') lines = csv.reader(file) r = 0 for line in lines: col = 0 for c in line: sheet2.row(r).write(col,c, style=xlwt.Style.default_style) #print(c,end=' ') col += 1 r += 1 sheet2.flush_row_data() file.close() workbook.save("csv2excel.xls")