python操作excel——openpyxl

一、概述

  python操作excel各个库对比:https://www.cnblogs.com/paul-liang/p/9187503.html

  操作老版本的excel文件使用xlrd:参考:https://segmentfault.com/a/1190000017485618

                 https://www.cnblogs.com/zhang-jun-jie/p/9273721.html

                        https://www.cnblogs.com/tynam/p/11204895.html 

  官方文档:https://openpyxl.readthedocs.io/en/stable/#usage-examples

二、入门

  1.安装:

pip install openpyxl

  conda:

conda install openpyxl

  2.创建excel文件

from openpyxl import Workbook

# 实例化一个工作簿
wb = Workbook()
# 激活工作簿
ws = wb.active

  3.打开已有文件

 from openpyxl  import load_workbook
wb2 = load_workbook('文件名称.xlsx')

 通过value访问单元格内容

from openpyxl import load_workbook


def main():
    file = 'D:\1.xlsx'
    wb = load_workbook(file)
    ws = wb.active
    # 通过value访问内容
    A1 = ws['A1'].value
    print(A1)


if __name__ == '__main__':
    main()

 

 4.单元格赋值

ws['A1'] = 42

  5.单元格访问

c = ws['A4']
d = ws.cell(row=4, column=2, value=10)

 一个实际遍历的案例:

    

from openpyxl import load_workbook


def main():
    file = 'D:\工作文件\浙江省教育厅\疫情数据\gdsqzmpqk.xlsx'
    wb = load_workbook(file)
    ws = wb.active
    # 可以通过最大行列进行输出遍历
    # 获取最大行
    row_max = ws.max_row
    # 获取最大列
    col_max = ws.max_column
    # for row in ws.rows:
    #     for cell in row:
    #         print(cell.value, '\t', end='')
    #     print()
    for i in range(2, row_max + 1):
        for j in range(1, col_max):
            print(ws.cell(row=i, column=j).value, '\t', end='')
        print()


if __name__ == '__main__':
    main()

 

 6.保存文件

wb.save('文件名称.xlsx')

  

  更多参考:https://blog.csdn.net/weixin_43094965/article/details/82226263

   读取excel导入mysql的案例:

from openpyxl import load_workbook
import pymysql


def write_db(t_sql, t_data):
    # 打开数据库连接
    db = pymysql.connect('127.0.0.1', 'root', 'root', 'test', charset='utf8')
    # 使用 cursor() 方法创建一个游标对象 cursor
    cursor = db.cursor()
    # 使用 execute()  方法执行 SQL 查询
    cursor.executemany(t_sql, t_data)
    # 提交
    db.commit()
    db.close()


def read_excel(filename):
    wb = load_workbook(filename)
    ws = wb.active
    cell_list = []
    row_list = []
    for row in tuple(ws.rows):
        # 清空列表
        cell_list.clear()
        for cell in row:
            cell_list.append(str(cell.value))
        row_list.append(cell_list)
    return row_list


if __name__ == '__main__':
    file = 'D:\1.xlsx'
    sql = 'INSERT INTO mpqk VALUES(%s,%s,%s,%s,%s,%s,%s,%s,%s)'
    data = read_excel(file)
    write_db(sql, data)
    print('SUCCESS!')

 

posted @ 2019-08-20 21:58  ---江北  阅读(503)  评论(0编辑  收藏  举报
TOP