设为首页 收藏本站
查看: 630|回复: 0

[经验分享] Python将excel导入到mysql中

[复制链接]
累计签到:1 天
连续签到:1 天
发表于 2015-11-30 07:58:01 | 显示全部楼层 |阅读模式
  分享一段前一段时间写的python代码



# encoding: utf-8
# !/usr/bin/python
import sys
import types
import datetime
import MySQLdb
import xlrd
from PyQt4 import QtGui

class MainWindow(QtGui.QDialog):
def __init__(self, parent=None):
QtGui.QDialog.__init__(self)
self.resize(450, 250)
self.setWindowTitle(u'导入员工信息')
self.excel_file_le = QtGui.QLineEdit(self)
self.excel_file_le.setDisabled(True)
self.db_url_le = QtGui.QLineEdit(self)
self.db_url_le.setPlaceholderText(u"数据库链接")
self.db_url_le.setText("localhost")
self.db_name_le = QtGui.QLineEdit(self)
self.db_name_le.setPlaceholderText(u"数据库名")
self.db_name_le.setText("sys")
self.db_user_le = QtGui.QLineEdit(self)
self.db_user_le.setPlaceholderText(u"用户名")
self.db_user_le.setText("root")
self.db_pwd_le = QtGui.QLineEdit(self)
self.db_pwd_le.setPlaceholderText(u"密码")
self.db_pwd_le.setText("root")
layout = QtGui.QVBoxLayout()
layout.addWidget(self.excel_file_le)
layout.addWidget(self.db_url_le)
layout.addWidget(self.db_name_le)
layout.addWidget(self.db_user_le)
layout.addWidget(self.db_pwd_le)
spacer_item = QtGui.QSpacerItem(20, 48, QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Expanding)
layout.addItem(spacer_item)
self.btnSelectExcelFile = QtGui.QPushButton(u'选择文件', self)
self.btnSelectExcelFile.clicked.connect(self.openFile)
self.btnTestConnection = QtGui.QPushButton(u'测试连接', self)
self.btnTestConnection.clicked.connect(self.test_connection)
self.btnConfirmImport = QtGui.QPushButton(u'确认导入', self)
self.btnConfirmImport.clicked.connect(self.import_excel_file)
button_layout = QtGui.QHBoxLayout()
spacer_item2 = QtGui.QSpacerItem(40, 20, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum)
button_layout.addItem(spacer_item2)
button_layout.addWidget(self.btnSelectExcelFile)
button_layout.addWidget(self.btnTestConnection)
button_layout.addWidget(self.btnConfirmImport)
layout.addLayout(button_layout)
self.setLayout(layout)
def test_connection(self):
try:
url_list = ["hosts=" + self.db_url_le.displayText(), "user=" + self.db_user_le.displayText(),
"passwd=" + self.db_pwd_le.displayText(),
"db=" + self.db_name_le.displayText(), "charset='utf8'"]
db = MySQLdb.connect(','.join(url_list).decode("utf-8"))
# QtGui.QMessageBox.
except Exception, e:
QtGui.QMessageBox.critical(self, u'错误', u'连接失败!')
print e
def import_excel_file(self):
if not self.excel_file_le.displayText():
QtGui.QMessageBox.critical(self, u'错误', u'请选择文件')
else:
self.read_excel_data(self, unicode(self.excel_file_le.displayText()))

def openFile(self):
file_list = QtGui.QFileDialog.getOpenFileNameAndFilter(self, u"选择导入文件", "", "Excel(*.xls)")
if (file_list[0]):
self.excel_file_le.setText(unicode(file_list[0]))
@staticmethod
def read_excel_data(self, path):
excel_workbook = xlrd.open_workbook(path)
sheet_data = excel_workbook.sheets()[0]
ncols = sheet_data.ncols
db = MySQLdb.connect("localhost", "root", "111111", "sys", charset='utf8')
cursor = db.cursor()
table_name = "pq_dw_info"
cursor.execute("desc " + table_name)
table_desc_list = cursor.fetchall()
table_desc_json = {}
for row in table_desc_list:
table_desc_json[row[0].encode("utf-8").lower()] = row
first_row_data = sheet_data.row_values(0)
excute_header_sql = "insert into " + table_name + "("
header_col_list = []
header_col_type_list = []
for i in range(0, ncols):
header_col_type_list.append(table_desc_json[(first_row_data.lower().encode("utf-8"))])
if i == 0:
header_col_list.append("dw_code")
continue
header_col_list.append(first_row_data)
excute_header_sql += ','.join(header_col_list) + \
",CREATED_BY_USER,CREATED_OFFICE,CREATED_DTM_LOC,RECORD_VERSION) values("
data_rows = []
__s_date = datetime.date(1899, 12, 31).toordinal() - 1
for i in range(1, sheet_data.nrows):
row_data_list = sheet_data.row_values(i)
# find data exsits
count_sql = "select count(1) from " + table_name + " where dw_code='" + str(int(row_data_list[0])) + "'"
cursor.execute(count_sql)
count_result = cursor.fetchall()
if count_result[0][0] != 0:
continue
sql = excute_header_sql
for j in range(0, ncols):
cell_data = row_data_list[j]
column_type = header_col_type_list[j][1]
column_default_value = header_col_type_list[j][4]
if j == 0:
sql += "'" + str(int(cell_data)) + "',"''
continue
if (column_type.startswith("int") or column_type.startswith("decimal") or column_type.startswith(
"bigint")):
if cell_data:
sql += unicode(cell_data) + ","
elif column_default_value:
sql += unicode(column_default_value) + ","
else:
sql += "null,"
elif (column_type.startswith("varchar") or column_type.startswith("char")
or column_type.startswith("longtext")):
if type(cell_data) is types.FloatType:
sql += "'" + str(int(cell_data)) + "',"''
else:
sql += "'" + unicode(cell_data) + "',"''
elif (column_type.startswith("date")):
if cell_data:
sql += "str_to_date('" + datetime.date.fromordinal(
__s_date + int(cell_data)).strftime("%Y-%m-%d") + "','%Y-%m-%d'),"''
else:
sql += "null,"
elif (column_type.startswith("datetime")):
if cell_data:
sql += "str_to_date('" + datetime.date.fromordinal(
__s_date + int(cell_data)).strftime("%Y-%m-%d") + "','%Y-%m-%d'),"''
else:
sql += "null,"
else:
sql += "'" + unicode(cell_data) + "',"''
sql += "'admin','admin',sysdate(),0)"
# print sql
            cursor.execute(sql)
try:
db.commit()
db.close()
except Exception, e:
db.rollback()
QtGui.QMessageBox.critical(self, u'错误', u'导入失败')
print e
print "import success!"

app = QtGui.QApplication(sys.argv)
main = MainWindow()
main.show()
sys.exit(app.exec_())
  小学生水平,偶尔拿来玩玩,现在公司项目都是安装在Windows上的,好想拿python当运维工具啊,看到很多小伙伴,使用python登录n台服务器,各种自动化脚本,羡慕。。。

运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-145091-1-1.html 上篇帖子: Python单元测试框架之pytest 下篇帖子: python 小爬虫的各种总结(二)
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表