zoukankan      html  css  js  c++  java
  • Python 操作Excel

    概述

    在使用Python处理数据的过程中常常需要读取或写入Excel表格,本文简要介绍使用xlrd读取Excel表格数据及使用XlsxWriter将数据写入到指定的sheet中。


    Code Sample
    • Excel读操作示例
    #coding=utf-8
    
    import xlrd
    
    #路径前加 r,读取的文件路径
    file_path = r'c:/Users/yuvmtest/Desktop/testdata.xlsx'
    
    #获取数据
    data = xlrd.open_workbook(file_path)
    
    #获取sheet
    table = data.sheet_by_name('Sheet0')
    
    #获取总行数
    nrows = table.nrows
    #获取总列数
    ncols = table.ncols
    
    print("总行数: %d,总列数: %d" % (nrows, ncols))
    
    #获取一行的数值,例如第2行
    rowvalue = table.row_values(2)
    
    #获取一列的数值,例如第3列
    col_values = table.col_values(3)
    
    #获取一个单元格的数值,例如第2行第3列
    cell_value = table.cell(2, 3).value
    
    print(rowvalue)
    print(col_values)
    
    
    • Excel 写操作示例
    
    # excel 写操作示例
    import xlsxwriter
    
    workbook = xlsxwriter.Workbook('d:yuexceltest.xlsx')  # 创建一个Excel文件
    worksheet = workbook.add_worksheet('test1')            # 创建一个sheet
    
    title = [U'列名1', U'列名2']                         # 表格title
    worksheet.write_row('A1', title)                    # title写入Excel
    
    headings = ['a', 'b', 'c', 'd']
    data = [
        [1, 2, 3],
        [2, 4, 6],
        [3, 6, 9]
    ]
    
    # 按行插入数据
    worksheet.write_row('A4', headings)
    # 按列插入数据
    
    worksheet.write_column('A5', data[0])
    worksheet.write_column('B5', data[1])
    worksheet.write_column('C5', data[2])
    
    # 插入多行数据
    
    for i in range(10):
        row = i + 8
        row_number = 'A' + str(row)
        worksheet.write_row(row_number, str(row*2))
    
    workbook.close()
    
    
    写操作效果展示

    image


    参考

    Creating Excel files with Python and XlsxWriter

  • 相关阅读:
    http 301 和 302的区别
    移动端与PHP服务端接口通信流程设计(增强版)
    导出大量数据到excel表
    c#中两种不同的存储过程调用与比较
    sql存储过程几个简单例子
    高级搜索指令
    SEO 百度后台主动推送链接
    C#利用Web Service实现短信发送(转)
    webservice测试实例
    克服演讲紧张的10个技巧
  • 原文地址:https://www.cnblogs.com/taro/p/9870087.html
Copyright © 2011-2022 走看看