from openpyxl import load_workbook
import math
from pyproj import Proj, transform
------------------------------
大地2000 (Gauss-Krüger) 转 WGS84 经纬度
------------------------------
def gauss2000_to_wgs84(E, N, zone=39, band=3):
"""
E, N: 大地2000 XY 坐标
zone: 带号
band: 带宽 (3 或 6)
返回: lon, lat (WGS84)
"""
自动缩放大数值
if E > 1e7 or N > 1e7:
scale = 1
while E / scale > 1e7 or N / scale > 1e7:
scale *= 10
E /= scale
N /= scale
# 中央经线
lon0 = zone * 3 if band == 3 else zone * 6 - 3
proj = Proj(
proj="tmerc",
lat_0=0,
lon_0=lon0,
k=1,
x_0=500000,
y_0=0,
ellps="GRS80"
)
lon, lat = proj(E, N, inverse=True)
return lon, lat
------------------------------
WGS84 转 GCJ-02 (高德/腾讯地图)
------------------------------
def wgs84_to_gcj02(lon, lat):
"""
lon, lat: WGS84
返回: lon, lat (GCJ-02)
"""
if out_of_china(lon, lat):
return lon, lat
dlat = _transformlat(lon - 105.0, lat - 35.0)
dlon = _transformlon(lon - 105.0, lat - 35.0)
radlat = lat / 180.0 * math.pi
a = 6378245.0
ee = 0.00669342162296594323
magic = math.sin(radlat)
magic = 1 - ee * magic * magic
sqrtmagic = math.sqrt(magic)
dlat = (dlat * 180.0) / ((a * (1 - ee)) / (magic * sqrtmagic) * math.pi)
dlon = (dlon * 180.0) / (a / sqrtmagic * math.cos(radlat) * math.pi)
mgLat = lat + dlat
mgLon = lon + dlon
return mgLon, mgLat
def out_of_china(lon, lat):
return not (73.66 < lon < 135.05 and 3.86 < lat < 53.55)
def _transformlat(x, y):
ret = -100.0 + 2.0x + 3.0 y + 0.2y y + 0.1x y + 0.2math.sqrt(abs(x))
ret += (20.0 math.sin(6.0x math.pi) + 20.0math.sin(2.0 xmath.pi)) * 2.0/3.0
ret += (20.0 math.sin(ymath.pi) + 40.0 math.sin(y/3.0math.pi)) * 2.0/3.0
ret += (160.0 math.sin(y/12.0math.pi) + 320 math.sin(y*math.pi/30.0)) * 2.0/3.0
return ret
def _transformlon(x, y):
ret = 300.0 + x + 2.0y + 0.1 xx + 0.1 xy + 0.1 math.sqrt(abs(x))
ret += (20.0math.sin(6.0 xmath.pi) + 20.0 math.sin(2.0x math.pi)) * 2.0/3.0
ret += (20.0math.sin(x math.pi) + 40.0math.sin(x/3.0 math.pi)) * 2.0/3.0
ret += (150.0math.sin(x/12.0 math.pi) + 300.0math.sin(x/30.0 math.pi)) * 2.0/3.0
return ret
------------------------------
读取 Excel 并转换
------------------------------
if name == "main ":
wb = load_workbook("file.xlsx")
ws = wb.active
for row in range(2, ws.max_row + 1):
E_cell = ws.cell(row=row, column=3).value
N_cell = ws.cell(row=row, column=4).value
if E_cell is None or N_cell is None:
continue
try:
E_cell = float(E_cell)
N_cell = float(N_cell)
except ValueError:
continue
# 1. 大地2000 -> WGS84
lon_wgs, lat_wgs = gauss2000_to_wgs84(E_cell, N_cell, 39, 3)
# 2. WGS84 -> GCJ-02
lon_gcj, lat_gcj = wgs84_to_gcj02(lon_wgs, lat_wgs)
# 写入 Excel 第 5 列
ws.cell(row=row, column=5, value=f"{lon_gcj:.6f}, {lat_gcj:.6f}")
wb.save("output_gcj02.xlsx")
print("转换完成!")