Python将xls导入mysql

这段Python代码演示了如何在Windows环境下将xls文件内容批量导入到MySQL数据库中。通过os模块遍历指定目录下的xls文件,使用xlrd库读取Excel数据,然后连接到MySQL数据库,设置字符集防止乱码,最后根据列数动态插入数据到不同表中。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

源码:

环境:win7

#!/usr/bin/python
#coding:gbk
print "你好"

import xlrd
import MySQLdb
import os


for fpathe,dirs,fs in os.walk("C:\\AAA\\python\\test4\\"):
  for f in fs:
    print os.path.join(fpathe,f)
   
    filename = os.path.join(fpathe,f)
#读取EXCEL中内容到数据库中

#for j in subjects:
#  print j
#  print "我的"
    wb = xlrd.open_workbook(filename)
    sh = wb.sheet_by_index(0)
    dfun=[]
    nrows = sh.nrows  #行数
    ncols = sh.ncols  #列数
    fo=[]

    fo.append(sh.row_values(0))
    for i in range(1,nrows):
        dfun.append(sh.row_values(i))

    conn=MySQLdb.connect(host='localhost',user='user',passwd='password',db='my_schema')
    cursor=conn.cursor()

    conn.set_character_set('utf8')  #设置导入mysql的字符,防止乱码产生
    cursor.execute('SET CHARACTER SET utf8;') 
    cursor.execute('SET NAMES utf8;') 
    cursor.execute('SET character_set_connection=utf8;')

#创建table
#cursor.execute("create table test4("+fo[0][0]+" varchar(100));")
#cursor.execute("truncate table data;")
#创建table属性
#for i in range(1,ncols):
#    cursor.execute("alter table data add "+fo[0][i]+" varchar(100);")
    val=''
    for i in range(0,ncols):
      val = val+'%s,'
    print dfun
    if (ncols == 20):
      cursor.executemany("insert into data20 values("+val[:-1]+");" ,dfun)

    elif (ncols == 21):
      cursor.executemany("insert into data21 values("+val[:-1]+");" ,dfun)

    elif (ncols == 22):
      cursor.executemany("insert into data22 values("+val[:-1]+");" ,dfun)

    else:
      print "有问题"
    

    conn.commit()


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值