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()')

猜你喜欢

转载自blog.csdn.net/wondervictor/article/details/79218192