使用Python读取Excel表格

时间:2020-05-28
本文章向大家介绍使用Python读取Excel表格,主要包括使用Python读取Excel表格使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#----------------------------------------------------------#
# Date    : xxxx-xx-xx                                     #
# Author  : Created by zhouwanchun.                        #
# Wechat  : loveoracle11g                                  #
# 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("\033[1;32m成功导入 [\033[0m" + columns + "\033[1;32m] 列 [\033[0m" + rows + "\033[1;32m] 行数据到MySQL数据库!\033[0m")

原文地址:https://www.cnblogs.com/zhouwanchun/p/12979010.html