Python Excel文件的讀寫操做(xlwt xlrd xlsxwriter)

 轉:http://www.javashuo.com/article/p-wbyfplhc-be.htmlhtml

Python語法簡潔清晰,做爲工做中經常使用的開發語言仍是很強大的(廢話)。python

python關於Excel的操做提供了xlwt和xlrd兩個的包做爲針對Excel通用操做的支持,跨平臺(Mac、Windows都可)。excel

xlrdxlrd目前支持讀寫xlsx(2007版)與xls(2003版),簡單的說明以下:htm

import xlrd

def open_excel(file='test.xls'):
    try:
        data = xlrd.open_workbook(file)
        # 經過索引獲取工做表
        sheet1 = data.sheets()[0]
        # 經過名稱獲取工做表
        sheet1 = data.sheet_by_name(u'sheet1')
        # 獲取table對象,根據table進行該工做表相關數據的讀取
        # 獲取行列
        row = sheet1.nrows
        col = sheet1.ncols

        # 獲取單元格的值
        cell_value = sheet1.cell(0, 1).value

        # 行列表數據
        for i in range(row):
            print sheet1.row_values(i)

        # 數據寫入
        # 單元格類型 0 empty,1 string, 2 number, 3 datetime, 4 boolean, 5 error
        # xf 擴展格式化
        xf = 0
        row_num = 1
        col_num = 1
        cell_type = 1
        sheet1.put_cell(row_num, col_num, cell_type, u'hello word', xf)
        return data
    except Exception, e:
        print str(e)

   xlwt則支持寫出2003版xls的包,具體操做如示例以下:對象

import xlwt

def write_excel2():
    # 設置通用樣式變量
    style_header = xlwt.easyxf(u'font: name 微軟雅黑, color-index black, bold on,height 240')
    workbook = xlwt.Workbook()
    worksheet = workbook.add_sheet(u'sheet1')
    # 設置第一列到單元格的寬度
    worksheet.col(0).width = 256 * 35
    # 設置該工做表單元格的寬度
    c = 1
    while c < 300:
        worksheet.col(c).width = 256 * 20
        c += 1
    col = 0
    # 循環設置表頭值
    header = [u'姓名', u'性別', u'年齡']
    for h in header:
        worksheet.write(0, col, h, style_header)
        col += 1
    # 保存到本地目錄,mac上後綴xlsx會報錯,xls正常。
    workbook.save('test.xls')

  xlsxwriter支持2007版的寫出blog

import xlsxwriter   #導入模塊
 
workbook = xlsxwriter.Workbook('new_excel.xlsx')     #新建excel表
 
worksheet = workbook.add_worksheet('sheet1')       #新建sheet(sheet的名稱爲"sheet1")
 
headings = ['Number','testA','testB']     #設置表頭
 
data = [
    ['2017-9-1','2017-9-2','2017-9-3','2017-9-4','2017-9-5','2017-9-6'],
    [10,40,50,20,10,50],
    [30,60,70,50,40,30],
]                                                              #本身造的數據
 
 
 
worksheet.write_row('A1',headings)
 
worksheet.write_column('A2',data[0])
worksheet.write_column('B2',data[1])
worksheet.write_column('C2',data[2])                   #將數據插入到表格中
 
 
workbook.close()          #將excel文件保存關閉,若是沒有這一行運行代碼會報錯
相關文章
相關標籤/搜索