各位用户为了找寻关于python 读取excel文件生成sql文件实例详解的资料费劲了很多周折。这里教程网为您整理了关于python 读取excel文件生成sql文件实例详解的相关资料,仅供查阅,以下为您介绍关于python 读取excel文件生成sql文件实例详解的详细内容
python 读取excel文件生成sql文件实例详解
学了python这么久,总算是在工作中用到一次。这次是为了从excel文件中读取数据然后写入到数据库中。这个逻辑用java来写的话就太重了,所以这次考虑通过python脚本来实现。
在此之前需要给python添加一个xlrd模块,这个模块是专门用来操作excel文件的。
在mac中可以通过easy_install xlrd命令实现自动安装模块
? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33import
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是轻松多了。
感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!
原文链接:https://my.oschina.net/u/241670/blog/349239