一聚教程网:一个值得你收藏的教程网站

最新下载

热门教程

实例:python 读取excel文件生成sql文件

时间:2017-05-14 编辑:简简单单 来源:一聚教程网

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

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

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

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

importxdrlib ,sys

importxlrd

defopen_excel(file=a.xlsx'):

  try:

    data=xlrd.open_workbook(file)#打开excel文件

    returndata

  exceptException,e:

    printstr(e)

defexcel_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)表示取第一行以后的行,因为第一行往往是表头

  forrownuminrange(1,nrows):

     row=table.row_values(rownum)

     ifrow:

       app={}

       foriincolindex:

          app[str(colnames[i]).encode("utf-8")]=str(row[i]).encode("utf-8")#将数据填入一个字典中,同时对数据进行utf-8转码,因为有些数据是unicode编码的

       list.append(app)#将字典加入列表中去

  returnlist

defmain():

  #colindex是一个数组,用来选择读取哪一列,因为往往excel中的一小部分才是我们需要的

  tables=excel_table_bycol(colindex=[1,4],table_name=u'areaCode')

  file=open('channel_area_code.sql','w')#创建sql文件,并开启写模式

  forrowintables:

    ifrow['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是轻松多了。

热门栏目