python读取excel文件生成sql文件

学了python这么久,总算是在工做中用到一次。此次是为了从excel文件中读取数据而后写入到数据库中。这个逻辑用java来写的话就过重了,因此此次考虑经过python脚原本实现。java

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

在mac中能够经过easy_install xlrd命令实现自动安装模块sql

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是轻松多了。数据库

相关文章
相关标签/搜索