有时堡垒机有权限设置 不能将excel导入表中。现在将excel中数据转为sql去执行
import xlrd #excel的read库
import xlwt #excel的write库
#打开的excel路径
openExcelName='E:/导数/sample.xlsx'
#打开的excel中的哪一个sheet
sheetName="Sheet"
#想插入的表
targetTableName="temp.transfer"
#想插入的字段
colName1="col1"
colName2="col2"
colName3="col3"
colName4="col4"
resutList=[];
def open_excel():
try:
book = xlrd.open_workbook(openExcelName)
except:
print("open excel file failed!")
try:
sheet = book.sheet_by_name(sheetName) #execl里面的worksheet1
return sheet
except:
print("locate worksheet in excel failed!")
def transfer_excel():
sheet = open_excel()
row_num = sheet.nrows #excel的总行数
col_num=sheet.ncols #excel的总列数
#第一行是表头 从二开始
for i in range(1, row_num):
row_data = sheet.row_values(i)
#value = (row_data[0],row_data[1],row_data[2],row_data[3])
#print("第"+str(i)+"行")
#print(row_data[0],row_data[1],row_data[2],row_data[3])
sql = "INSERT INTO "+targetTableName+"("+colName1+","+colName2+","+colName3+","+colName4+")VALUES("+str(row_data[0])+","+str(row_data[1])+","+str(row_data[2])+","+str(row_data[3])+");"
global resutList #因为要修改这个list 必须声明这个变量为全局的,不然全局的变量会变成局部的,拿不出去用
resutList.append(sql) #用stringbuffer
print(sql)
def list_write_to_txt():
#写入这个excel文件 写的权限(没有会创建)
f = open("E:/导数/sample2.txt", "w")
for line in resutList:
f.write(line + "\n")
f.close()
def list_write_to_excel():
#excel的写入功能
xls = xlwt.Workbook()
sheet = xls.add_sheet("Sheet1")
for i in range(0, len(resutList)):
print("结果的" + resutList[i])
#写入第一列数据
sheet.write(i,1, resutList[i])
xls.save("E:/导数/target.xlsx")
#打开excel
open_excel()
#excel转化为sql的list
transfer_excel()
#list写入txt文本
list_write_to_txt()
#list写入excel
list_write_to_excel()
print(resutList)