標籤:
#-*- coding:utf-8 -*-# 處理 excel 中的 area 為 Mysql insert 語句import xlrd, json, codecs, os# data = xlrd.open_workbook(‘101.xls‘)data = xlrd.open_workbook(‘C:\Users\Administrator\Desktop\changanyiyuan.xlsx‘)# table = data.sheets()[0]table = data.sheet_by_index(0)# try hospitalJson = codecs.open(‘C:\Users\Administrator\Desktop\changanyiyuan.json‘,‘a+‘,‘utf-8‘)hospitalJson.truncate(0)hospitalJson.write(‘[‘) # 先寫入數組頭hospitalJsonInsert = codecs.open(‘C:\Users\Administrator\Desktop\hospitalJsonInsert.json‘,‘a+‘,‘utf-8‘)hospitalJsonInsert.truncate(0)hospitalJsonInsert.write(‘insert into department(hospital_id, pid, name, rank, create_time, modify_time) values‘)# 取出表格的第一行作為 json 的 key (javascript object notation)attribute = table.row_values(0)# 除第一行以外的資料放入一個 dict jsonAll = []contents = {}for index_r in range(1,table.nrows): for index_c in range(table.ncols): contents[attribute[index_c]] = table.cell(index_r, index_c).value # cell 儲存格的一個屬性並非方法 # print contents hospitalJson.write("%s,\n" %json.dumps(contents,ensure_ascii=False,sort_keys=True, indent=4)) hospitalJsonInsert.write(‘(2265, -1, \‘%s\‘ ,%d, now(), now()),‘%(table.cell(index_r, 3).value, table.cell(index_r, 5).value)) # jsonAll.append(json.dumps(contents,ensure_ascii=False,sort_keys=True, indent=4))# print hospitalJson.tell()# hospitalJson.seek(0)# print hospitalJson.tell()hospitalJson.seek(-2, os.SEEK_END)hospitalJson.truncate()hospitalJson.write(‘]‘) # 數組結束# hospitalJson.write(json.dumps(contents,ensure_ascii=False,sort_keys=True, indent=4)) # 少了 ensure_ascii=False 參數就不能寫中文進檔案?hospitalJsonInsert.seek(-1, os.SEEK_END)hospitalJsonInsert.truncate()hospitalJsonInsert.write(‘;‘)# hospitalJson.write("%s" % jsonAll)hospitalJson.close()hospitalJsonInsert.close()# (`id`, `hospital_id`, `pid`, `name`, `rank`, `create_time`, `modify_time`)# 寫成 mysql 語句# hospitalJsonInsert.write(‘( 2265, -1, \‘%s\‘ ,%s, now(), now())‘%(table.cell(index_r, 3), table.cell(index_r, 5)))
使用 xlrd 模組實現對excel 的讀取、excel轉json 、excel 轉 mysql insert 語句