实现概括:
- 可在Excel表格中添加下拉框列表
- 列表在web页面中自动添加
- 读取Excel表格数据转换为json格式
- 用占位符对齐城市和地区编码
- 用ajax动态添加标签
展示效果:
文件列表:
Excel截图:
html
<input name="d" class="code" readonly="readonly"/>
<select name="city" class="city" dir="auto" ></select>
css
.city{
width: 50px;
height: 30px;
}
.code{
position: absolute;
z-index: 9999;
left: 10px;
top:11px;
width: 30px;
height: 23px;
border: none;
outline: none;
}
js
$("select").change(function () { // 下拉框change属性,详情见菜鸟教程和w3c
$("input").val($(this).val()); // 把选中的值通过input标签展示出
console.log($(this).val());
});
$(function () {
$.ajax({
type:"get",
url:"area_code.json",
dataType:"json",
success:function (d) {
let data = d.option;
let select = $(".city");
for (let i = 0; i < data.length; i++) {
let a = data[i].code;
a = a.replace(/&.*;/,""); // 因为value属性中不会识别占位符,所以需要将占位符去掉
console.log(a);
if (i === 0) {
$(".code").val(a) // 默认把第一个options的value值展示出来
}
let options="<option value='" + data[i].code + "'>" + data[i].country + "</option>";
select.append(options); // 在select标签下添加options标签
}
}
});
});
创建json.py
import pandas as pd # 导入pandas库
fp = pd.read_excel("area_code.xlsx") # 读取xlsx文件,注意文件不能是加密格式
country = fp['country'].tolist() # 将country列读取出来并转换为数组类型
code1 = fp['code'].tolist() # 将code列读取出来并转换为数组类型
code = [] # 准备接收转为字符串类型的code
for i in range(len(code1)):
code.append("+" + str(code1[i])) # 因为tolist转出来的数字是整形,所以将它转为字符串类型并在前面加上“+”号
options = ""
for index, i in enumerate(country):
result = i.ljust(10, 'a') # 在国家右边填充“a”这个字符,使其长度为10
result = result.replace('a', ' ') # 将a字符转换为 这个占位符(一个中文宽度)
area = code[index].rjust(4, 's') # 在code左边填充“s”字符使其长度为4
area = area.replace('s', ' ') # 将s字符转换为 这个占位符(半个中文宽度)
result = "{\"country\":" + "\"" + result + area + "\", \"code\":\"" + area + "\"}," # \"表示转义
options = options + result
options = options[:-1] # 输出为一行
options = "{\"option\":["+options+"]}" # 调整格式为json格式
with open("area_code.json", "w", encoding="utf-8") as f: # 保存文件
f.write(options)