python3.6 write/read excel


import xlrd

def read_excel():
    #    workbook
    workbook = xlrd.open_workbook('demo.xls')
    #    sheet    
    worksheets = workbook.sheet_names()
    print('worksheets is %s' %worksheets)
    #   sheet1
    worksheet1 = workbook.sheet_by_name(u'demo1')
    """
    #        
    worksheet1 = workbook.sheets()[0]
    worksheet1 = workbook.sheet_by_index(0)
    #    sheet  
    for worksheet_name in worksheets:
    worksheet = workbook.sheet_by_name(worksheet_name)
    """
    #  sheet1    row
    num_rows = worksheet1.nrows
    for curr_row in range(num_rows):
        row = worksheet1.row_values(curr_row)
        print('row%s is %s' %(curr_row,row))
    #  sheet1    col
    num_cols = worksheet1.ncols
    for curr_col in range(num_cols):
        col = worksheet1.col_values(curr_col)
        print('col%s is %s' %(curr_col,col))
    #  sheet1      cell
    for rown in range(num_rows):
        for coln in range(num_cols):
            cell = worksheet1.cell_value(rown,coln)
            print (cell)

if __name__ == '__main__':
    read_excel()
    print (u'read demo.xls    ')
import os
import xlwt


def set_style(name, height, bold = False):
    style = xlwt.XFStyle()

    font = xlwt.Font()
    font.name = name
    font.bold = bold
    font.color_index = 4
    font.height = height

    style.font = font
    return style


def write_excel():
    workbook = xlwt.Workbook(encoding='utf-8')

    data_sheet = workbook.add_sheet('demo1')
    row0 = [u'    ', u'    ', 'CRNTI', 'CELL-ID']
    row1 = [u'  ', '15:50:33-15:52:14', 22706, 4190202]

    for i in range(len(row0)):
        data_sheet.write(0, i, row0[i], set_style('Times New Roman', 220, True))
        data_sheet.write(1, i, row1[i], set_style('Times New Roman', 220, True))

    workbook.save('demo.xls')


if __name__ == '__main__':
    write_excel()
    print (u'  demo.xlsx    ')
import os
import xlwt,xlrd
from xlutils.copy import copy

def config_add_row(new_server=None):
    if new_server is None:
        new_server = []
    print(new_server)

    filename = r'Server_config.xls'
    workbook = xlrd.open_workbook(filename)
    sheet = workbook.sheet_by_index(0)
    rowNum = sheet.nrows
    colNum = sheet.ncols
    newbook = copy(workbook)
    newsheet = newbook.get_sheet(0)

    # append new row in the tail of the excel
    for coln in range(colNum):
        newsheet.write(rowNum, coln, new_server[coln])
        print (new_server[coln])

    # override to save
    newbook.save(filename)
    print (u'Successfully to add new row in %s',filename)



if __name__ == '__main__':
    #write_excel()
    #excelwrite()
    #config_add_row1()
    new_row = ['intel' ,'10.245.36.99','/intel/','/intel/intel.log','SLES12','111111','END']
    config_add_row(new_row)
    print (u'Successfully to execute main()')