将xlsx文件中的sheet表导入到mysql数据表中

我们在平时工作中需要将xlsx表和数据库表中的相匹配的字段导入到数据库表中,并且两张表的匹配的顺序也不一定一致,还不一定知道到底有多少个匹配字段,因此就需要首先判断这些内容,直接上代码:

bk = xlrd.open_workbook(self.FilePath.toPlainText())  # 打开选中的Excel文件
sh = bk.sheet_by_name(self.SheetName.currentText()) # 激活选中的Sheet表格
row_num = sh.nrows # 总行数
# print(row_num)
data_list = [] # 定义列表
# for i in range(1, row_num): #从内容第一行(逻辑为0)开始循环

for i in range(0, 1): # 输出第一行(表头),列表形式
row_data = sh.row_values(i) # 行内容列表

# print(row_data) # 输出选中sheet的字段,为列表类型
# print(self.TableList.currentRow())
# print(self.TableList.item(self.TableList.currentRow()).text())
table_name = self.TableList.item(self.TableList.currentRow()).text() # 输出选中的列表框中的项,currentRow()为当前列表中的值
try:
conn = pymysql.connect(host='localhost', user='root', password='975136', db='ztedatabase',
charset='utf8')
except:
QMessageBox.information(self, '数据库连接错误:', '无法连接到SQL Server服务器,请确认后重试!!!')
exit(0)
cur = conn.cursor()
sql = 'select * from %s' % (table_name) # 执行变量为table_name的查询
cur.execute(sql)
col_name_list = [tuple[0] for tuple in cur.description] # 输出选中表的字段,为列表类型
# print(col_name_list)
# -----------------------------------------字段匹配----------------------------------------------------------
pipei = []
header = ""
for i in range(len(row_data)):
# print(row_data[i])
if row_data[i] in col_name_list: # 逐个判断源表字段是否存在于数据库表中
pipei.append(row_data[i]) # 将匹配字段添加到列表“pipei”中
header = header + ',' + row_data[i] # 将列表内容转换为以逗号相隔的字符串模式
header1 = header[1:] # 截取字符串,去除最前面的逗号
# print(header1)
if len(pipei) == 0:
QMessageBox.information(self, '表错误警告:', '源表和目标表无匹配字段,请重新选择文件后再操作!')
return
else:
QMessageBox.information(self, '报告:', '源表和目标表共存在' + str(len(pipei)) + '个匹配字段!')
seat = []
for k in range(len(pipei)): # 循环匹配后的字段列表
if pipei[k] in row_data: # 如果匹配后的字段存在于Sheet表头--当然存在
seat.append(row_data.index(pipei[k])) # 将匹配后的每个字段在sheet表中的位置追加到seat列表)
cur.execute('delete from %s' % (table_name)) # 删除源表内容
conn.commit()
if self.YN.isChecked() == True: # 是否去除字头(中兴特有的规则,默认去除5行)
head_num = 5
else:
head_num = 1
nums = 0
space = 0
for i in range(head_num, row_num): # 开始循环内容
row_data = sh.row_values(i)
data = {}
for index, key in enumerate(sh.row_values(0)):
if index in seat: # 如果字段名在seat列表中
if row_data[index] == '': # 如果表格中需要导入的字段为空
# print(index)
aa = " " # 将表格内容用0进行替换,避免不导入
space += 1
print('错误提示:Excel表中第%s行“%s”字段存在空格,请纠正!' % (i, sh.row_values(0)[index]))
else:
aa = row_data[index]
data[key] = aa
data_list.append(data)
# print(data)
table = table_name
keys = ', '.join(data.keys())
# print(data.keys(1))
values = ', '.join(['%s'] * len(data))
# print(table)
# print(keys) # 输出以逗号相隔的字头列表,为字符串内省
# print(values) # 输出匹配字段数量个的“%s”

sql = 'INSERT INTO {table}({keys}) VALUES ({values})'.format(table=table, keys=keys,
values=values) # 巧妙的sql语句
try:
cur.execute(sql, tuple(data.values()))
# print('Successful')
# conn.commit()
nums += 1
conn.commit()
except:
print('第%s条记录导入失败' % (i + 1))
# print(tuple(data.values()))
conn.rollback()
if nums == row_num - 1:
QMessageBox.information(self, '报告:', '源表共' + str(row_num - 1) + '条记录,已经全部成功导入到目标表!')
else:
QMessageBox.information(self, '报告:',
'源表共' + str(row_num - 1) + '条记录,实际导入' + str(nums) + '条,请查找匹配字段中是否存在空数据!')
cur.close()
conn.close()

原文地址:https://www.cnblogs.com/huangyz-xy/p/12734640.html