python 操做 excel

讀excel

import xlrd
fname = './test.xls'
bk = xlrd.open_workbook(fname)
shxrange = range(bk.nsheets)
nrows = sh.nrows
ncols = sh.ncols
for i in range(1, nrows):
    row_data = sh.row_values(i)
    row_list.append(row_data)

根據表單sheet的是個數組能夠遍歷全部表單python

sh = bk.sheet_by_index(0)
sh = bk.sheet_by_name('xxx')

兩種方式獲取表單
sh.cell_value(0,0)
定位獲取單元值數組

寫excel

# -*- coding: utf-8 -*-
#導入xlwt模塊
import xlwt
# 建立一個Workbook對象,這就至關於建立了一個Excel文件
book = xlwt.Workbook(encoding='utf-8', style_compression=0)
'''
Workbook類初始化時有encoding和style_compression參數
encoding:設置字符編碼,通常要這樣設置:w = Workbook(encoding='utf-8'),就能夠在excel中輸出中文了。
默認是ascii。固然要記得在文件頭部添加:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
style_compression:表示是否壓縮,不經常使用。
'''
#建立一個sheet對象,一個sheet對象對應Excel文件中的一張表格。
# 在電腦桌面右鍵新建一個Excel文件,其中就包含sheet1,sheet2,sheet3三張表
sheet = book.add_sheet('test', cell_overwrite_ok=True)
# 其中的test是這張表的名字,cell_overwrite_ok,表示是否能夠覆蓋單元格,實際上是Worksheet實例化的一個參數,默認值是False
# 向表test中添加數據
sheet.write(0, 0, 'EnglishName')  # 其中的'0-行, 0-列'指定表中的單元,'EnglishName'是向該單元寫入的內容
sheet.write(1, 0, 'Marcovaldo')
txt1 = '中文名字'
sheet.write(0, 1, txt1.decode('utf-8'))  # 此處須要將中文字符串解碼成unicode碼,不然會報錯
txt2 = '馬可瓦多'
sheet.write(1, 1, txt2.decode('utf-8'))
 
# 最後,將以上操做保存到指定的Excel文件中
book.save(r'e:\test1.xls')  # 在字符串前加r,聲明爲raw字符串,這樣就不會處理其中的轉義了。不然,可能會報錯

修改已有excel

import xlwt;  
import xlrd;  
#import xlutils;  
from xlutils.copy import copy;  
   
#init xls file  
#styleBlueBkg= xlwt.easyxf('pattern: pattern solid, fore_colour sky_blue;');  
#styleBold   = xlwt.easyxf('font: bold on');  
styleBoldRed  =xlwt.easyxf('font: color-index red, bold on');  
headerStyle=styleBoldRed;  
wb=xlwt.Workbook();  
ws=wb.add_sheet(gConst['xls']['sheetName']);  
ws.write(0,0,"Header",        headerStyle);  
ws.write(0,1,"CatalogNumber", headerStyle);  
ws.write(0,2,"PartNumber",    headerStyle);  
wb.save(gConst['xls']['fileName']);  
   
   
#open existed xls file  
#newWb = xlutils.copy(gConst['xls']['fileName']);  
#newWb = copy(gConst['xls']['fileName']);  
oldWb=xlrd.open_workbook(gConst['xls']['fileName']);  
printoldWb;#<xlrd.book.Book object at 0x000000000315C940>  
newWb=copy(oldWb);  
printnewWb;#<xlwt.Workbook.Workbook object at 0x000000000315F470>  
newWs=newWb.get_sheet(0);  
newWs.write(1,0,"value1");  
newWs.write(1,1,"value2");  
newWs.write(1,2,"value3");  
print"write new values ok";  
newWb.save(gConst['xls']['fileName']);  
print"save with same name ok";
相關文章
相關標籤/搜索