zoukankan      html  css  js  c++  java
  • 使用Python读取Excel表格

    #!/usr/bin/env python3
    # -*- coding: utf-8 -*-
    #----------------------------------------------------------#
    # Date    : xxxx-xx-xx                                     #
    # Author  : Created by zhouwanchun.                        #
    # Wechat  : lovemysql3306                                  #
    # Function: This scripts function is ...                   #
    # Version : 1.1                                            #
    #----------------------------------------------------------#
    
    # 导入模块
    import xlrd
    import mysql.connector
    
    # 打开数据所在的工作簿,以及选择存有数据的工作表
    excel = xlrd.open_workbook("./1.xlsx")
    sheet = excel.sheet_by_name("Sheet1")
    
    # 连接MySQL数据库
    conn = mysql.connector.connect(
        host='10.0.0.11',
        port=3306,
        user='zhouwanchun',
        password='123',
        charset='utf8'
    )
    
    # 创建游标
    sql_cmd = conn.cursor()
    
    # 创建插入的SQL语句
    insert_mysql = 'insert into app01.t1(id, c1, c2, c3, intime) values(%s, %s, %s, %s, %s)'
    
    # 创建一个for循环迭代读取Excel文件每行数据,从第二行开始是要跳过标题行。
    for r in range(1, sheet.nrows):
        id =     int(sheet.cell(r,0).value)
        # print(id, type(id))
        c1 =     str(sheet.cell(r,1).value)
        # print(c1, type(c1))
        c2 =     str(sheet.cell(r,2).value)
        # print(c2, type(c2))
        c3 =     str(int(sheet.cell(r,3).value))
        # print(c3, type(c3))
        intime = str(sheet.cell(r,4).value)
        # print(intime, type(intime))
        values = (id, c1, c2, c3, intime)
    
        # 执行SQL语句
        sql_cmd.execute(insert_mysql, values)
    
    sql_cmd.close()
    conn.commit()
    conn.close()
    
    columns = str(sheet.ncols)
    rows = str(sheet.nrows)
    print("33[1;32m成功导入 [33[0m" + columns + "33[1;32m] 列 [33[0m" + rows + "33[1;32m] 行数据到MySQL数据库!33[0m")

  • 相关阅读:
    Channel使用技巧
    Flask开发技巧之异常处理
    后端开发使用pycharm的技巧
    python单元测试
    Docker入门介绍
    python高阶函数的使用
    python内置模块collections介绍
    python中@property装饰器的使用
    三次握手四次挥手
    python类方法@classmethod与@staticmethod
  • 原文地址:https://www.cnblogs.com/zhouwanchun/p/12979010.html
Copyright © 2011-2022 走看看