python 读取excel文件生成sql文件实例详解

yipeiwu_com7年前Python基础

python 读取excel文件生成sql文件实例详解

学了python这么久,总算是在工作中用到一次。这次是为了从excel文件中读取数据然后写入到数据库中。这个逻辑用java来写的话就太重了,所以这次考虑通过python脚本来实现。

在此之前需要给python添加一个xlrd模块,这个模块是专门用来操作excel文件的。

在mac中可以通过easy_install xlrd命令实现自动安装模块

import xdrlib ,sys
import xlrd
def open_excel(file= a.xlsx'):
  try:
    data = xlrd.open_workbook(file)#打开excel文件
    return data
  except Exception,e:
    print str(e)

def excel_table_bycol(file='a.xlsx',colindex=[0],table_name='Sheet1'):
  data = open_excel(file)
  table = data.sheet_by_name(table_name)#获取excel里面的某一页
  nrows = table.nrows#获取行数
  colnames = table.row_values(0)#获取第一行的值,作为key来使用,对于不同的excel文件可以进行调整
  list = []
  #(1,nrows)表示取第一行以后的行,因为第一行往往是表头
  for rownum in range(1,nrows):
     row = table.row_values(rownum)
     if row:
       app = {}
       for i in colindex:
          app[str(colnames[i]).encode("utf-8")] = str(row[i]).encode("utf-8")#将数据填入一个字典中,同时对数据进行utf-8转码,因为有些数据是unicode编码的
       list.append(app)#将字典加入列表中去
  return list
def main():
  #colindex是一个数组,用来选择读取哪一列,因为往往excel中的一小部分才是我们需要的
  tables = excel_table_bycol(colindex=[1,4],table_name=u'areaCode')
  file = open('channel_area_code.sql','w')#创建sql文件,并开启写模式
  for row in tables:
    if row['area_code'] != '':
        file.write("update table_name set para1='%s' where para2='%s';\n"%(row['para1'],row['para2']))#往文件里写入sql语句
if __name__=="__main__":
  main()

这并非是一个通用的python脚本,还是需要根据excel文件的格式作出一些调整,但是代码并不复杂,开发速度也很快,比以前用java是轻松多了。

感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

相关文章

利用Python的Twisted框架实现webshell密码扫描器的教程

好久以来都一直想学习windows中得iocp技术,即异步通信,但是经过长时间研究别人的c++版本,发现过于深奥了,有点吃力,不过幸好python中的twisted技术的存在方便了我。...

Python 读写文件的操作代码

Python读写文件模式 1、r 打开只读文件,该文件必须存在。 2、r+ 打开可读写的文件,该文件必须存在。 3、w 打开只写文件,若文件存在则文件长度清为0,即该文件内容会...

python 解决flask 图片在线浏览或者直接下载的问题

目前是把图片存在mongodb数据库,实现一个方法,比如 访问 /get_pic/ID 能实现图片在浏览器打开,添加了一个状态,比如?filename=1.png,实现图片直接下载, 需...

python 使用装饰器并记录log的示例代码

1.首先定义一个log文件 # -*- coding: utf-8 -*- import os import time import logging import sys log_d...

python对常见数据类型的遍历解析

字符串遍历 >>> a_str = "hello itcast" >>> for char in a_str: ... print(char,...