import xlrd import json # import requests # pip install xlrd # pip install requests def openWorkbook(): # 讀取excel表的數據 workbook = xlrd.open_workbook(r'E:/case.xlsx') # 選取需要讀取數據的那一頁 sheet = workbook.sheet_by_index(0) # 獲得行數和列數 rows = sheet.nrows cols = sheet.ncols #創建一個key、value合並單元格的值 unitCell = {} for crange in sheet.merged_cells: rs, re, cs, ce = crange #print(str(rs)+","+str(re)+","+str(cs)+","+str(ce)) merged_cell_val = sheet.cell(rs, cs).value #print(merged_cell_val) sRow = rs sCol = cs; while sRow < re : while sCol < ce : unitCell[str(sRow) + "-" + str(sCol)] = merged_cell_val sCol = sCol+1 sRow = sRow+1 sCol = cs; # 創建一個數組用來存儲excel中的數據 #print(unitCell) p = [] for i in range(1, rows): d = {} for j in range(0, cols): q = '%s' % sheet.cell(0, j).value key = str(i) + "-" + str(j) print(key) if key not in unitCell: d[q] = sheet.cell(i, j).value if key in unitCell: print(unitCell[key]) d[q] = unitCell[key] ap = [] for k, v in d.items(): if isinstance(v, float): # excel中的值默認是float,需要進行判斷處理,通過'"%s":%d','"%s":"%s"'格式化數組 ap.append('"%s":%d' % (k, v)) else: ap.append('"%s":"%s"' % (k, v)) s = '{%s}' % (','.join(ap)) # 繼續格式化 p.append(s) t = '[%s]' % (','.join(p)) # 格式化 data=json.dumps(t,ensure_ascii=False) return data.replace("\\","") # with open('student4.json',"w",encoding='utf-8') as f: # f.write(t) #openWorkbook() #url="http://111.111.111.111:8000/pushdata/" #headers={"Content-Type":"application/json"} data=openWorkbook() print(data) #re=requests.post(url=url,headers=headers,data=data) #print(re.text)