feat: 新增Excel报表导出功能

This commit is contained in:
dmy
2026-01-01 16:25:55 +08:00
parent 6454a2c01e
commit 34b0d70309

48
main.py
View File

@@ -687,6 +687,45 @@ def export_to_dxf(turbines, substation, connections_details, filename):
except Exception as e:
print(f"导出DXF失败: {e}")
# 6.6 导出Excel报表
def export_to_excel(connections_details, filename):
"""
将设计方案详情导出为Excel文件
:param connections_details: evaluate_design返回的'details'列表
"""
data = []
for conn in connections_details:
data.append({
'Source': conn['source'],
'Target': conn['target'],
'Horizontal Length (m)': conn['horizontal_length'],
'Vertical Length (m)': conn['vertical_length'],
'Effective Length (m)': conn['length'],
'Cable Type (mm²)': conn['cable']['cross_section'],
'Current (A)': conn['cable']['current'],
'Power (MW)': conn['power'],
'Resistance (Ω)': conn['cable']['resistance'],
'Cost (¥)': conn['cable']['cost']
})
df = pd.DataFrame(data)
# 汇总统计
summary = {
'Total Cost (¥)': df['Cost (¥)'].sum(),
'Total Effective Length (m)': df['Effective Length (m)'].sum(),
'Total Vertical Length (m)': df['Vertical Length (m)'].sum()
}
summary_df = pd.DataFrame([summary])
try:
with pd.ExcelWriter(filename) as writer:
df.to_excel(writer, sheet_name='Cable Schedule', index=False)
summary_df.to_excel(writer, sheet_name='Summary', index=False)
print(f"成功导出Excel文件: {filename}")
except Exception as e:
print(f"导出Excel失败: {e}")
# 6. 可视化函数
def visualize_design(turbines, substation, connections, title, ax=None, show_costs=True):
"""可视化集电线路设计方案"""
@@ -888,19 +927,22 @@ def compare_design_methods(excel_path=None, n_clusters_override=None):
output_filename = 'wind_farm_design_comparison.png'
plt.savefig(output_filename, dpi=300)
# 导出最佳方案 DXF
# 导出最佳方案 DXF 和 Excel
if excel_path:
base_name = os.path.splitext(os.path.basename(excel_path))[0]
dir_name = os.path.dirname(excel_path)
# 如果 dir_name 为空(即当前目录),则直接使用文件名,或者使用 os.path.join('', ...) 也是安全的
dxf_filename = os.path.join(dir_name, f"{base_name}.dxf")
# 如果 dir_name 为空(即当前目录),则直接使用文件名
dxf_filename = os.path.join(dir_name, f"{base_name}_design.dxf")
excel_out_filename = os.path.join(dir_name, f"{base_name}_design.xlsx")
else:
dxf_filename = 'wind_farm_design.dxf'
excel_out_filename = 'wind_farm_design.xlsx'
# Use the connection details from the best evaluation
# Note: We need the turbine DataFrame corresponding to the best method to get cluster IDs if possible,
# but export_to_dxf mainly needs coordinates which are constant.
export_to_dxf(clustered_turbines, substation, kmeans_evaluation['details'], dxf_filename)
export_to_excel(kmeans_evaluation['details'], excel_out_filename)
# plt.show()