(copy)python操作excel


 

python操作excel除了讀就是寫。

1 從讀開始 xlrd  下載地址:http://pypi.python.org/pypi/xlrd

導入:import xlrd

打開excel: file = xlrd.open_workbook('demo.xls')

查看文件中包含sheet的名稱:file.sheet_names()

得到第一個工作表,或者通過索引順序 或 工作表名稱
sheet = file.sheets()[0]
sheet = file.sheet_by_index(0)
sheet = file.sheet_by_name(u'Sheet1')

獲取行數和列數
nrows = sheet.nrows
ncols = sheet.ncols

循環行,得到索引的列表
for rownum in range(sheet.nrows):
    print sheet.row_values(rownum)

獲取整行和整列的值(數組)
sheet.row_values(i)
sheet.col_values(i)

單元格(索引獲取)
cell_A1 = sheet.cell(0,0).value
cell_C4 = sheet.cell(2,3).value

分別使用行列索引
cell_A1 = sheet.row(0)[0].value
cell_A2 = sheet.col(1)[0].value

2 寫 xlwt 下載地址:http://pypi.python.org/pypi/xlrd

導入xlwt import xlwt

新建一個excel文件

file = xlwt.Workbook() #注意這里的Workbook首字母是大寫,無語吧

新建一個sheet

sheet = file.add_sheet('sheet name')

寫入數據sheet.write(行,列,value)

sheet.write(0,0,'test')

如果對一個單元格重復操作,會引發
returns error:
# Exception: Attempt to overwrite cell:
# sheetname=u'sheet 1' rowx=0 colx=0

所以在打開時加cell_overwrite_ok=True解決

sheet = file.add_sheet('sheet name',cell_overwrite_ok=True)

保存文件

file.save('demo.xls')

另外,使用style

style = xlwt.XFStyle() #初始化樣式

font = xlwt.Font() #為樣式創建字體

font.name = 'Times New Roman'

font.bold = True

style.font = font #為樣式設置字體

sheet.write(0, 0, 'some bold Times text', style) # 使用樣式

xlwt 允許單元格或者整行地設置格式。還可以添加鏈接以及公式。

源代碼中的模塊:

  dates.py, 展示如何設置不同的數據格式

  hyperlinks.py, 展示如何創建超鏈接  

  merged.py, 展示如何合並格子

  row_styles.py, 展示如何應用Style到整行格子中.


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM