使用Python代碼處理Excel

使用Python操做Excel不是什麼難事,須要用到兩個Lib, python-xlrd,python-xlwtpython

安裝

pip install xlrd xlwt 支持xls,xlsx格式ide

寫Excel

建立一個文件 workbook = xlwt.Workbook(encoding='utf-8') 增長一個表單 booksheet = workbook.add_sheet('Sheet 1') 增長一行 row = booksheet.row(i) 增長一列 col = booksheet.col(j) 爲某個單元格賦值 booksheet.write(i, j, 'Test') row.write(j, 'Test') col.write(i, 'Test') 注意: 在add_sheet時, 置參數cell_overwrite_ok=True, 能夠覆蓋原單元格中數據。 cell_overwrite_ok默認爲False, 覆蓋的話, 會拋出異常.excel

import xlwt
workbook = xlwt.Workbook(encoding='utf-8')
booksheet = workbook.add_sheet('Sheet 1', cell_overwrite_ok=True)
workboot.add_sheet('Sheet 2')
DATA = (('學號', '姓名', '年齡', '性別', '成績'),
             (1001, 'AAAA', 23, '男', 98),
             (1002, 'BBBB', 21, '女', 90),
             (1003, 'CCCC', 24, '女', 100),
             (1004, 'DDDD', 22, '女', 86),
             (1005, 'EEEE', 25, '女', 88),)

for i, row in enuerate(DATA):
    for j, col in enuerate(row):
        booksheet.write(i, j, col)
booksheet.col(0).width=10
workbook.save('成績單.xls')

讀Excel

獲取一個文件 workbook = xlrd.open_workbook('成績單.xls') 獲取文件中表單數量
workbook.nsheets 獲取一個表單
workbook.sheets()[i], workbook.sheet_by_index(i) workbook.sheet_by_name(u'Sheet1') 獲取行,列數
sheet.nrows, sheet.ncols 獲取整行,列數據
sheet.row(i), sheet.col(j) 獲取某個單元格數據
sheet.cell(i, j).value sheet.row(i)[j].value sheet.col(j)[i].valuecode

import xlrd
workbook = xlrd.open_workbook('成績單.xls')
print "There are {} sheets in the workbook".format(workbook.nsheets)
for booksheet in workbook.sheets():
    print booksheet.name
    for row in xrange(booksheet.nrows):
        for col in xrange(booksheet.ncols):
            print xlrd.cellname(row, col)
            print booksheet.cell(row, col).value

要想更詳細的瞭解,能夠參加python-excel官網,以及09年EuroPython slide

相關文章
相關標籤/搜索