python操作excel

作者: 不可分类者bubble | 来源:发表于2018-06-27 09:17 被阅读0次

    1、导入xlrd库

    import xlrd

    path = '1.xlsx'

    wb = xlrd.open_workbook(path)

    first_sheet = wb.sheet_by_index(0) #通过索引

    #first_sheet = wb.sheet_by_name('Sheet1')#通过名称获取

    maxRows = first_sheet.nrows #总行数

    maxCols = first_sheet.ncols #总列数

    list = []

    for i in range(maxRows):

    # first_sheet.row_values(i) 第i行所有数据

    # first_sheet..col_values(i) 第i列所有数据

        list.append(first_sheet.row_values(i))

    print(list)

    2、导入load_workbook库

    from openpyxl import load_workbook

    wb = load_workbook(path, data_only=True) #导入工作簿

    sheet_name_list = wb.get_sheet_names() #得到所有的表格--sheet

    ws = wb.get_sheet_by_name(sheet_name_list[0]) #通过名称获取

    maxRows = len(ws.rows) #总行数

    maxCols = len(ws.columns) #总列数

    rows = ws.rows #表格所有行内容列表

    list = []

    for i in range(maxRows):

    for j in range(maxCols):

    list.append((rows[i][j].value))

    print(list)

    3、导入pandas 库(这个库最方便简单)

    import pandas as pd

    d = pd.read_excel(path, sheetname=[0]) #获取第一个sheet

    df = d[0] #获取第一个sheet的所有值

    data = pd.DataFrame()

    list = []

    for index, row in df.iterrows():

    run = row['run']

    desc = row['desc']

    method = row['method']

    list.append([run, desc, method])

    print(list)

    data.to_csv('list.csv')

    代码示例:

    excel原始数据 输出数据

    相关文章

      网友评论

        本文标题:python操作excel

        本文链接:https://www.haomeiwen.com/subject/vcomyftx.html