Files
KEPS/Keps.WinForms/Services/ExcelReportService.cs
2026-03-20 08:52:16 +09:00

836 lines
44 KiB
C#

using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using Keps.WinForms.Models;
using OfficeOpenXml;
using OfficeOpenXml.Style;
namespace Keps.WinForms.Services
{
/// <summary>
/// 실 추출 결과를 Excel 워크북(.xlsx)으로 내보내는 서비스입니다.
/// </summary>
public sealed class ExcelReportService
{
/// <summary>
/// 실 추출 결과와 관련 시트를 포함한 Excel 워크북을 저장합니다.
/// </summary>
/// <param name="filePath">저장할 파일 경로.</param>
/// <param name="electionName">선거명 또는 연월.</param>
/// <param name="areaName">시도명.</param>
/// <param name="clusterRows">군집 요약 행 목록(모드 시트 등에 사용).</param>
/// <param name="result">실 추출 결과 DTO.</param>
public void ExportRealExtractionWorkbook(string filePath, string electionName, string areaName, List<ClusterSummaryRow> clusterRows, RealExtractionResult result)
{
if (result == null)
{
throw new InvalidOperationException("추출 결과가 없습니다.");
}
string dir = Path.GetDirectoryName(filePath);
if (!string.IsNullOrWhiteSpace(dir))
{
Directory.CreateDirectory(dir);
}
using (ExcelPackage package = new ExcelPackage())
{
List<string> candidateNames = (result.CandidateNames ?? new List<string>()).ToList();
List<string> candidateVoteKeys = (result.CandidateVoteKeys ?? new List<string>()).ToList();
List<string> candidateRatioKeys = (result.CandidateRatioKeys ?? new List<string>()).ToList();
NormalizeCandidateLists(candidateNames, candidateVoteKeys, candidateRatioKeys);
WriteExtractedSheet(package.Workbook.Worksheets.Add(areaName + "-추출결과"), electionName, areaName, candidateNames, candidateVoteKeys, result.ExtractedRows ?? new List<ExtractionRow>(), result.PopulationRows ?? new List<ExtractionRow>(), result);
WriteVerificationSummarySheet(package.Workbook.Worksheets.Add(areaName + "-자가 검증-요약분석"), electionName, areaName, candidateNames, result.VerificationRows ?? new List<VerificationSummaryRow>(), result.ClusterMax);
WriteVerificationDetailSheet(package.Workbook.Worksheets.Add(areaName + "-자가 검증-세부분석"), electionName, areaName, candidateNames, candidateVoteKeys, result.ExtractedRows ?? new List<ExtractionRow>(), result.VerificationRows ?? new List<VerificationSummaryRow>(), result.ClusterMax);
WriteFinalStatusSheet(package.Workbook.Worksheets.Add(areaName + "-최종 투표소 추출현황"), electionName, areaName, candidateNames, candidateVoteKeys, result.PopulationRows ?? new List<ExtractionRow>(), result.ClusterMax);
WriteClusterListSheet(package.Workbook.Worksheets.Add(areaName + "-층별 시군구 리스트"), electionName, areaName, result.PopulationRows ?? new List<ExtractionRow>());
WriteModeSheet(package.Workbook.Worksheets.Add(areaName + "-기준설정 Mode"), electionName, clusterRows ?? new List<ClusterSummaryRow>(), result.PopulationRows ?? new List<ExtractionRow>());
WriteModeTargetSheet(package.Workbook.Worksheets.Add(areaName + "-기준설정 Mode Target"), clusterRows ?? new List<ClusterSummaryRow>(), result.PopulationRows ?? new List<ExtractionRow>());
package.SaveAs(new FileInfo(filePath));
}
}
/// <summary>
/// 추출 결과 시트를 작성합니다(클러스터별 표본과 모집단 요약 포함).
/// </summary>
/// <param name="ws">대상 워크시트.</param>
/// <param name="electionName">선거명 또는 연월.</param>
/// <param name="areaName">시도명.</param>
/// <param name="candidateNames">후보자 표시명 목록(최소 3개로 보정됨).</param>
/// <param name="candidateVoteKeys">후보자 득표 키 목록(최소 3개로 보정됨).</param>
/// <param name="rows">추출 표본 행 목록.</param>
/// <param name="populationRows">모집단 행 목록.</param>
/// <param name="result">추출 실행 메타(정렬/오프셋 등).</param>
private static void WriteExtractedSheet(ExcelWorksheet ws, string electionName, string areaName, List<string> candidateNames, List<string> candidateVoteKeys, List<ExtractionRow> rows, List<ExtractionRow> populationRows, RealExtractionResult result)
{
int rowIndex = 1;
foreach (IGrouping<int, ExtractionRow> clusterGroup in rows.GroupBy(x => x.ClusterNo).OrderBy(x => x.Key))
{
int sampleCount = clusterGroup.Count();
MergeAndSet(ws, rowIndex, 1, rowIndex, 15, BuildClusterTitle(result, clusterGroup.Key, sampleCount));
ws.Cells[rowIndex, 1].Style.Font.Bold = true;
rowIndex++;
SetExtractHeader(ws, rowIndex, candidateNames, result.ClusterMax);
rowIndex += 2;
List<ExtractionRow> clusterPopulation = populationRows.Where(x => x.ClusterNo == clusterGroup.Key).ToList();
MergeAndSet(ws, rowIndex, 1, rowIndex, 8, clusterGroup.Key + " 층(군집) 전체");
ws.Cells[rowIndex, 9].Value = clusterPopulation.Sum(x => GetVoteByKey(x, candidateVoteKeys[0]));
ws.Cells[rowIndex, 10].Value = clusterPopulation.Sum(x => GetVoteByKey(x, candidateVoteKeys[1]));
ws.Cells[rowIndex, 11].Value = clusterPopulation.Sum(x => GetVoteByKey(x, candidateVoteKeys[2]));
ws.Cells[rowIndex, 12].Value = clusterPopulation.Sum(x => x.TotalCandidateVoteCount);
ws.Cells[rowIndex, 13].Value = ComputeClusterActualRatio(clusterPopulation, candidateVoteKeys[0]);
ws.Cells[rowIndex, 14].Value = ComputeClusterActualRatio(clusterPopulation, candidateVoteKeys[1]);
ws.Cells[rowIndex, 15].Value = ComputeClusterActualRatio(clusterPopulation, candidateVoteKeys[2]);
FillHeaderGray(ws, rowIndex, 1, rowIndex, 15);
rowIndex++;
foreach (ExtractionRow row in clusterGroup.OrderBy(x => x.ClusterOrder))
{
ws.Cells[rowIndex, 1].Value = row.ClusterOrder;
ws.Cells[rowIndex, 2].Value = electionName;
ws.Cells[rowIndex, 3].Value = row.AreaName;
ws.Cells[rowIndex, 4].Value = row.DistrictName;
ws.Cells[rowIndex, 5].Value = row.ClusterNo;
ws.Cells[rowIndex, 6].Value = BuildTownLabel(row);
ws.Cells[rowIndex, 7].Value = row.PollingPlaceNo;
ws.Cells[rowIndex, 8].Value = row.ElectorateCount;
ws.Cells[rowIndex, 9].Value = GetVoteByKey(row, candidateVoteKeys[0]);
ws.Cells[rowIndex, 10].Value = GetVoteByKey(row, candidateVoteKeys[1]);
ws.Cells[rowIndex, 11].Value = GetVoteByKey(row, candidateVoteKeys[2]);
ws.Cells[rowIndex, 12].Value = row.TotalCandidateVoteCount;
ws.Cells[rowIndex, 13].Value = ComputeDisplayedRowRatio(row, candidateVoteKeys[0]);
ws.Cells[rowIndex, 14].Value = ComputeDisplayedRowRatio(row, candidateVoteKeys[1]);
ws.Cells[rowIndex, 15].Value = ComputeDisplayedRowRatio(row, candidateVoteKeys[2]);
rowIndex++;
}
MergeAndSet(ws, rowIndex, 1, rowIndex, 15, "---------------------------------------------------");
rowIndex++;
}
ApplyCommonFormatting(ws, 15);
SetNumberFormats(ws, 4, rowIndex - 1, new[] { 8, 9, 10, 11, 12 }, "#,##0");
SetNumberFormats(ws, 4, rowIndex - 1, new[] { 13, 14, 15 }, "0.0");
}
/// <summary>
/// 추출 결과 시트의 헤더(타이틀/열 병합/후보 라벨)를 설정합니다.
/// </summary>
/// <param name="ws">대상 워크시트.</param>
/// <param name="rowIndex">헤더를 쓸 시작 행.</param>
/// <param name="candidateNames">후보자 표시명 목록.</param>
/// <param name="clusterMax">층(군집) 최대 개수.</param>
private static void SetExtractHeader(ExcelWorksheet ws, int rowIndex, List<string> candidateNames, int clusterMax)
{
for (int col = 1; col <= 8; col++)
{
ws.Cells[rowIndex, col, rowIndex + 1, col].Merge = true;
}
ws.Cells[rowIndex, 12, rowIndex + 1, 12].Merge = true;
ws.Cells[rowIndex, 1].Value = "순번";
ws.Cells[rowIndex, 2].Value = "선거명";
ws.Cells[rowIndex, 3].Value = "시도명";
ws.Cells[rowIndex, 4].Value = "선거구명";
ws.Cells[rowIndex, 5].Value = "층(" + clusterMax + "개층)";
ws.Cells[rowIndex, 6].Value = "읍면동";
ws.Cells[rowIndex, 7].Value = "투표구명";
ws.Cells[rowIndex, 8].Value = "선거인수";
ws.Cells[rowIndex, 9].Value = "기호1";
ws.Cells[rowIndex, 10].Value = "기호2";
ws.Cells[rowIndex, 11].Value = "기호3";
ws.Cells[rowIndex, 12].Value = "유효\n득표수계";
ws.Cells[rowIndex, 13].Value = "기호1";
ws.Cells[rowIndex, 14].Value = "기호2";
ws.Cells[rowIndex, 15].Value = "기호3";
ws.Cells[rowIndex + 1, 9].Value = candidateNames[0];
ws.Cells[rowIndex + 1, 10].Value = candidateNames[1];
ws.Cells[rowIndex + 1, 11].Value = candidateNames[2];
ws.Cells[rowIndex + 1, 13].Value = "득표율";
ws.Cells[rowIndex + 1, 14].Value = "득표율";
ws.Cells[rowIndex + 1, 15].Value = "득표율";
FillHeaderGray(ws, rowIndex, 1, rowIndex + 1, 15);
ws.Cells[rowIndex, 1, rowIndex + 1, 15].Style.WrapText = true;
}
/// <summary>
/// 자가 검증-요약분석 시트를 작성합니다(전체/층별 득표율 및 오차 요약).
/// </summary>
/// <param name="ws">대상 워크시트.</param>
/// <param name="electionName">선거명 또는 연월.</param>
/// <param name="areaName">시도명.</param>
/// <param name="candidateNames">후보자 표시명 목록.</param>
/// <param name="rows">검증 요약 행 목록.</param>
/// <param name="clusterMax">군집(층) 최대 개수.</param>
private static void WriteVerificationSummarySheet(ExcelWorksheet ws, string electionName, string areaName, List<string> candidateNames, List<VerificationSummaryRow> rows, int clusterMax)
{
ws.Cells[1, 1].Value = areaName;
MergeAndSet(ws, 1, 2, 1, 7, "정렬(" + clusterMax + "개층)");
MergeAndSet(ws, 1, 8, 1, 18, electionName + " 층화 후 득표율 기준 자가(self) 검증");
ws.Cells[2, 1, 3, 1].Merge = true;
ws.Cells[2, 2, 3, 2].Merge = true;
ws.Cells[2, 3, 3, 3].Merge = true;
ws.Cells[2, 4, 3, 4].Merge = true;
MergeAndSet(ws, 2, 5, 2, 7, "추출 득표율");
MergeAndSet(ws, 2, 8, 2, 10, "실제 득표율");
MergeAndSet(ws, 2, 11, 2, 14, "전체 오차비교");
MergeAndSet(ws, 2, 15, 2, 18, "층내 오차비교");
ws.Cells[2, 1].Value = "투표구수";
ws.Cells[2, 2].Value = "해당층";
ws.Cells[2, 3].Value = "층의비율";
ws.Cells[2, 4].Value = "추출\n투표구수";
ws.Cells[3, 5].Value = candidateNames[0];
ws.Cells[3, 6].Value = candidateNames[1];
ws.Cells[3, 7].Value = candidateNames[2];
ws.Cells[3, 8].Value = candidateNames[0];
ws.Cells[3, 9].Value = candidateNames[1];
ws.Cells[3, 10].Value = candidateNames[2];
ws.Cells[3, 11].Value = "기호1오차";
ws.Cells[3, 12].Value = "기호2오차";
ws.Cells[3, 13].Value = "기호3오차";
ws.Cells[3, 14].Value = "오차합";
ws.Cells[3, 15].Value = "기호1오차";
ws.Cells[3, 16].Value = "기호2오차";
ws.Cells[3, 17].Value = "기호3오차";
ws.Cells[3, 18].Value = "오차합";
FillHeaderGray(ws, 1, 1, 3, 18);
int rowIndex = 4;
foreach (VerificationSummaryRow row in rows)
{
ws.Cells[rowIndex, 1].Value = row.RowLabel == "전체" ? row.SampleCount + "개" : null;
ws.Cells[rowIndex, 2].Value = row.RowLabel;
ws.Cells[rowIndex, 3].Value = row.ClusterRatio;
ws.Cells[rowIndex, 4].Value = row.SampleCount;
ws.Cells[rowIndex, 5].Value = row.Extracted1;
ws.Cells[rowIndex, 6].Value = row.Extracted2;
ws.Cells[rowIndex, 7].Value = row.Extracted3;
ws.Cells[rowIndex, 8].Value = row.Actual1;
ws.Cells[rowIndex, 9].Value = row.Actual2;
ws.Cells[rowIndex, 10].Value = row.Actual3;
ws.Cells[rowIndex, 11].Value = row.WeightedError1;
ws.Cells[rowIndex, 12].Value = row.WeightedError2;
ws.Cells[rowIndex, 13].Value = row.WeightedError3;
ws.Cells[rowIndex, 14].Value = row.WeightedErrorSum;
ws.Cells[rowIndex, 15].Value = row.RowLabel == "전체" ? "-" : (object)row.InClusterError1;
ws.Cells[rowIndex, 16].Value = row.RowLabel == "전체" ? "-" : (object)row.InClusterError2;
ws.Cells[rowIndex, 17].Value = row.RowLabel == "전체" ? "-" : (object)row.InClusterError3;
ws.Cells[rowIndex, 18].Value = row.RowLabel == "전체" ? "-" : (object)row.InClusterErrorSum;
if (row.RowLabel == "전체")
{
FillHeaderGray(ws, rowIndex, 1, rowIndex, 18);
}
rowIndex++;
}
ApplyCommonFormatting(ws, 18);
SetNumberFormats(ws, 4, rowIndex - 1, new[] { 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18 }, "0.0");
SetNumberFormats(ws, 4, rowIndex - 1, new[] { 3 }, "0.00000");
}
/// <summary>
/// 자가 검증-세부분석 시트를 작성합니다(층/구간별 상세 지표 포함).
/// </summary>
/// <param name="ws">대상 워크시트.</param>
/// <param name="electionName">선거명 또는 연월.</param>
/// <param name="areaName">시도명.</param>
/// <param name="candidateNames">후보자 표시명 목록.</param>
/// <param name="candidateVoteKeys">후보자 득표 키 목록.</param>
/// <param name="rows">추출 표본 행 목록.</param>
/// <param name="summaryRows">검증 요약 행 목록.</param>
/// <param name="clusterMax">군집(층) 최대 개수.</param>
private static void WriteVerificationDetailSheet(ExcelWorksheet ws, string electionName, string areaName, List<string> candidateNames, List<string> candidateVoteKeys, List<ExtractionRow> rows, List<VerificationSummaryRow> summaryRows, int clusterMax)
{
ws.Cells[1, 1].Value = areaName;
MergeAndSet(ws, 1, 2, 1, 7, "정렬(" + clusterMax + "개층)");
MergeAndSet(ws, 1, 8, 1, 18, electionName + " 층화 후 득표율 기준 자가(self) 검증-세부분석");
ws.Cells[2, 1, 3, 1].Merge = true;
ws.Cells[2, 2, 3, 2].Merge = true;
ws.Cells[2, 3, 3, 3].Merge = true;
ws.Cells[2, 4, 3, 4].Merge = true;
MergeAndSet(ws, 2, 5, 2, 7, "추출 득표율");
MergeAndSet(ws, 2, 8, 2, 10, "실제 득표율");
MergeAndSet(ws, 2, 11, 2, 14, "선거구 오차비교");
MergeAndSet(ws, 2, 15, 2, 18, "층내 오차비교");
ws.Cells[2, 1].Value = "해당층";
ws.Cells[2, 2].Value = "투표구별";
ws.Cells[2, 3].Value = "층의비율";
ws.Cells[2, 4].Value = "추출\n투표구수";
ws.Cells[3, 5].Value = candidateNames[0];
ws.Cells[3, 6].Value = candidateNames[1];
ws.Cells[3, 7].Value = candidateNames[2];
ws.Cells[3, 8].Value = candidateNames[0];
ws.Cells[3, 9].Value = candidateNames[1];
ws.Cells[3, 10].Value = candidateNames[2];
ws.Cells[3, 11].Value = "기호1오차";
ws.Cells[3, 12].Value = "기호2오차";
ws.Cells[3, 13].Value = "기호3오차";
ws.Cells[3, 14].Value = "오차합";
ws.Cells[3, 15].Value = "기호1오차";
ws.Cells[3, 16].Value = "기호2오차";
ws.Cells[3, 17].Value = "기호3오차";
ws.Cells[3, 18].Value = "오차합";
FillHeaderGray(ws, 1, 1, 3, 18);
VerificationSummaryRow total = summaryRows.FirstOrDefault(x => x.RowLabel == "전체");
int rowIndex = 4;
if (total != null)
{
WriteSummaryLikeDetailRow(ws, rowIndex++, total, "전체", "전체", false);
}
foreach (IGrouping<int, ExtractionRow> group in rows.GroupBy(x => x.ClusterNo).OrderBy(x => x.Key))
{
VerificationSummaryRow clusterSummary = summaryRows.FirstOrDefault(x => x.RowLabel == group.Key + " 층");
if (clusterSummary != null)
{
WriteSummaryLikeDetailRow(ws, rowIndex++, clusterSummary, group.Key + " 층계", null, true);
}
foreach (ExtractionRow row in group.OrderBy(x => x.ClusterOrder))
{
decimal rowRatio1 = ComputeDisplayedRowRatio(row, candidateVoteKeys[0]);
decimal rowRatio2 = ComputeDisplayedRowRatio(row, candidateVoteKeys[1]);
decimal rowRatio3 = ComputeDisplayedRowRatio(row, candidateVoteKeys[2]);
ws.Cells[rowIndex, 2].Value = BuildTownLabel(row) + " " + row.PollingPlaceNo + "투";
ws.Cells[rowIndex, 4].Value = "-";
ws.Cells[rowIndex, 5].Value = rowRatio1;
ws.Cells[rowIndex, 6].Value = rowRatio2;
ws.Cells[rowIndex, 7].Value = rowRatio3;
if (total != null)
{
decimal err1 = Round1(rowRatio1 - total.Actual1);
decimal err2 = Round1(rowRatio2 - total.Actual2);
decimal err3 = Round1(rowRatio3 - total.Actual3);
ws.Cells[rowIndex, 11].Value = err1;
ws.Cells[rowIndex, 12].Value = err2;
ws.Cells[rowIndex, 13].Value = err3;
ws.Cells[rowIndex, 14].Value = Round1(Math.Abs(err1) + Math.Abs(err2) + Math.Abs(err3));
}
if (clusterSummary != null)
{
decimal err1 = Round1(rowRatio1 - clusterSummary.Actual1);
decimal err2 = Round1(rowRatio2 - clusterSummary.Actual2);
decimal err3 = Round1(rowRatio3 - clusterSummary.Actual3);
ws.Cells[rowIndex, 15].Value = err1;
ws.Cells[rowIndex, 16].Value = err2;
ws.Cells[rowIndex, 17].Value = err3;
ws.Cells[rowIndex, 18].Value = Round1(Math.Abs(err1) + Math.Abs(err2) + Math.Abs(err3));
}
rowIndex++;
}
}
ApplyCommonFormatting(ws, 18);
SetNumberFormats(ws, 4, rowIndex - 1, new[] { 5, 6, 7, 11, 12, 13, 14, 15, 16, 17, 18 }, "0.0");
SetNumberFormats(ws, 4, rowIndex - 1, new[] { 3 }, "0.00000");
}
/// <summary>
/// 요약 행 데이터를 세부 형식과 동일하게 한 줄로 출력합니다.
/// </summary>
/// <param name="ws">대상 워크시트.</param>
/// <param name="rowIndex">기록할 시작 행.</param>
/// <param name="row">요약 데이터.</param>
/// <param name="label1">왼쪽 라벨.</param>
/// <param name="label2">오른쪽 라벨.</param>
/// <param name="includeClusterError">군집 내 오차 컬럼 포함 여부.</param>
private static void WriteSummaryLikeDetailRow(ExcelWorksheet ws, int rowIndex, VerificationSummaryRow row, string label1, string label2, bool includeClusterError)
{
ws.Cells[rowIndex, 1].Value = label1;
ws.Cells[rowIndex, 2].Value = label2;
ws.Cells[rowIndex, 3].Value = row.ClusterRatio;
ws.Cells[rowIndex, 4].Value = row.SampleCount;
ws.Cells[rowIndex, 5].Value = row.Extracted1;
ws.Cells[rowIndex, 6].Value = row.Extracted2;
ws.Cells[rowIndex, 7].Value = row.Extracted3;
ws.Cells[rowIndex, 8].Value = row.Actual1;
ws.Cells[rowIndex, 9].Value = row.Actual2;
ws.Cells[rowIndex, 10].Value = row.Actual3;
ws.Cells[rowIndex, 11].Value = row.WeightedError1;
ws.Cells[rowIndex, 12].Value = row.WeightedError2;
ws.Cells[rowIndex, 13].Value = row.WeightedError3;
ws.Cells[rowIndex, 14].Value = row.WeightedErrorSum;
if (includeClusterError)
{
ws.Cells[rowIndex, 15].Value = row.InClusterError1;
ws.Cells[rowIndex, 16].Value = row.InClusterError2;
ws.Cells[rowIndex, 17].Value = row.InClusterError3;
ws.Cells[rowIndex, 18].Value = row.InClusterErrorSum;
}
}
/// <summary>
/// 최종 투표소 추출현황 시트를 작성합니다(모집단 내 각 행과 후보 득표수/비율 표시).
/// </summary>
/// <param name="ws">대상 워크시트.</param>
/// <param name="electionName">선거명 또는 연월.</param>
/// <param name="areaName">시도명.</param>
/// <param name="candidateNames">후보자 표시명 목록.</param>
/// <param name="candidateVoteKeys">후보자 득표 키 목록.</param>
/// <param name="rows">모집단 행 목록.</param>
/// <param name="clusterMax">군집(층) 최대 개수.</param>
private static void WriteFinalStatusSheet(ExcelWorksheet ws, string electionName, string areaName, List<string> candidateNames, List<string> candidateVoteKeys, List<ExtractionRow> rows, int clusterMax)
{
ws.Cells[1, 1].Value = areaName;
ws.Cells[3, 1].Value = clusterMax + "개층";
ws.Cells[1, 2, 3, 2].Merge = true;
ws.Cells[1, 3, 3, 3].Merge = true;
ws.Cells[1, 2].Value = "ID";
ws.Cells[1, 3].Value = "시군구";
MergeAndSet(ws, 1, 4, 1, 9, "Target 선거 출구조사 투표소 현황");
MergeAndSet(ws, 1, 10, 1, 13, "정렬기준(" + electionName + ")");
ws.Cells[1, 14, 3, 14].Merge = true;
ws.Cells[1, 15, 3, 15].Merge = true;
ws.Cells[1, 14].Value = "투표소\n중복여부";
ws.Cells[1, 15].Value = "비고 - 기타";
for (int col = 4; col <= 10; col++)
{
if (col != 10)
{
ws.Cells[2, col, 3, col].Merge = true;
}
}
ws.Cells[2, 4].Value = "투표구명";
ws.Cells[2, 5].Value = "유권자수";
ws.Cells[2, 6].Value = "투표 장소(건물명)";
ws.Cells[2, 7].Value = "투표 장소(주소)";
ws.Cells[2, 8].Value = "자동\n추출";
ws.Cells[2, 9].Value = "조정";
ws.Cells[2, 10, 3, 10].Merge = true;
ws.Cells[2, 10].Value = "득표수\n계";
MergeAndSet(ws, 2, 11, 2, 13, "득표율");
ws.Cells[3, 11].Value = candidateNames[0];
ws.Cells[3, 12].Value = candidateNames[1];
ws.Cells[3, 13].Value = candidateNames[2];
FillHeaderGray(ws, 1, 1, 3, 15);
int rowIndex = 4;
foreach (IGrouping<int, ExtractionRow> group in rows.GroupBy(x => x.ClusterNo).OrderBy(x => x.Key))
{
ws.Cells[rowIndex, 1].Value = group.Key + "층계";
ws.Cells[rowIndex, 2].Value = "-";
ws.Cells[rowIndex, 3].Value = "-";
ws.Cells[rowIndex, 4].Value = "-";
ws.Cells[rowIndex, 5].Value = group.Sum(x => x.EligibleVoterCount);
ws.Cells[rowIndex, 6].Value = "-";
ws.Cells[rowIndex, 7].Value = "-";
ws.Cells[rowIndex, 8].Value = "-";
ws.Cells[rowIndex, 10].Value = group.Sum(x => x.TotalCandidateVoteCount);
ws.Cells[rowIndex, 11].Value = ComputeClusterActualRatio(group.ToList(), candidateVoteKeys[0]);
ws.Cells[rowIndex, 12].Value = ComputeClusterActualRatio(group.ToList(), candidateVoteKeys[1]);
ws.Cells[rowIndex, 13].Value = ComputeClusterActualRatio(group.ToList(), candidateVoteKeys[2]);
FillHeaderGray(ws, rowIndex, 1, rowIndex, 15);
rowIndex++;
foreach (ExtractionRow row in group.OrderBy(x => x.OriginalOrder))
{
ws.Cells[rowIndex, 1].Value = row.ClusterNo;
ws.Cells[rowIndex, 2].Value = row.OriginalOrder;
ws.Cells[rowIndex, 3].Value = row.DistrictName;
ws.Cells[rowIndex, 4].Value = row.EupMyeonDong + " " + row.PollingPlaceNo + "투";
ws.Cells[rowIndex, 5].Value = row.EligibleVoterCount;
ws.Cells[rowIndex, 6].Value = row.BuildingName;
ws.Cells[rowIndex, 7].Value = row.Address1;
ws.Cells[rowIndex, 8].Value = (row.IsAutoSelected || row.IsAdjustedSelected) ? "★" : null;
ws.Cells[rowIndex, 9].Value = row.IsAdjustedSelected ? "★" : (row.IsAutoSelected ? "★" : null);
ws.Cells[rowIndex, 10].Value = row.TotalCandidateVoteCount;
ws.Cells[rowIndex, 11].Value = ComputeDisplayedRowRatio(row, candidateVoteKeys[0]);
ws.Cells[rowIndex, 12].Value = ComputeDisplayedRowRatio(row, candidateVoteKeys[1]);
ws.Cells[rowIndex, 13].Value = ComputeDisplayedRowRatio(row, candidateVoteKeys[2]);
ws.Cells[rowIndex, 14].Value = row.DuplicateFlag;
ws.Cells[rowIndex, 15].Value = row.Note;
rowIndex++;
}
}
ApplyCommonFormatting(ws, 15);
SetNumberFormats(ws, 4, rowIndex - 1, new[] { 5, 10 }, "#,##0");
SetNumberFormats(ws, 4, rowIndex - 1, new[] { 11, 12, 13 }, "0.0");
}
/// <summary>
/// 층별 시군구 리스트 시트를 작성합니다(군집별로 읍면동 묶음 출력).
/// </summary>
/// <param name="ws">대상 워크시트.</param>
/// <param name="electionName">선거명 또는 연월.</param>
/// <param name="areaName">시도명.</param>
/// <param name="rows">모집단 행 목록.</param>
private static void WriteClusterListSheet(ExcelWorksheet ws, string electionName, string areaName, List<ExtractionRow> rows)
{
ws.Cells[1, 1].Value = "선거명";
ws.Cells[1, 2].Value = "시도명";
ws.Cells[1, 3].Value = "선거구명";
ws.Cells[1, 4].Value = "군집";
ws.Cells[1, 5].Value = "읍면동";
FillHeaderGray(ws, 1, 1, 1, 5);
int rowIndex = 2;
foreach (var row in rows.GroupBy(x => new { x.DistrictName, x.ClusterNo }).OrderBy(x => x.Key.ClusterNo).ThenBy(x => x.Key.DistrictName))
{
ws.Cells[rowIndex, 1].Value = electionName;
ws.Cells[rowIndex, 2].Value = areaName;
ws.Cells[rowIndex, 3].Value = row.Key.DistrictName;
ws.Cells[rowIndex, 4].Value = row.Key.ClusterNo;
rowIndex++;
}
ApplyCommonFormatting(ws, 5);
}
/// <summary>
/// 기준설정 Mode 시트를 작성합니다(군집 요약과 모집단 정보를 활용한 기준표).
/// </summary>
/// <param name="ws">대상 워크시트.</param>
/// <param name="electionName">선거명 또는 연월.</param>
/// <param name="rows">군집 요약 행 목록.</param>
/// <param name="populationRows">모집단 행 목록.</param>
private static void WriteModeSheet(ExcelWorksheet ws, string electionName, List<ClusterSummaryRow> rows, List<ExtractionRow> populationRows)
{
MergeAndSet(ws, 1, 1, 1, 7, electionName);
ws.Cells[2, 1].Value = "층";
ws.Cells[2, 2].Value = "투표구수";
ws.Cells[2, 3].Value = "층의비율";
ws.Cells[2, 4].Value = "유권자수";
ws.Cells[2, 5].Value = "투표인수";
ws.Cells[2, 6].Value = "후보별득표수계";
ws.Cells[2, 7].Value = "투표율";
FillHeaderGray(ws, 1, 1, 2, 7);
int rowIndex = 3;
foreach (ClusterSummaryRow row in rows.OrderBy(x => x.ClusterNo))
{
List<ExtractionRow> clusterPopulation = populationRows.Where(x => x.ClusterNo == row.ClusterNo).ToList();
int electorate = clusterPopulation.Sum(x => x.ElectorateCount);
int voteCount = clusterPopulation.Sum(x => x.VoteCount);
int totalVotes = clusterPopulation.Sum(x => x.TotalCandidateVoteCount);
ws.Cells[rowIndex, 1].Value = row.ClusterNo + " 층";
ws.Cells[rowIndex, 2].Value = row.PollingPlaceCount;
ws.Cells[rowIndex, 3].Value = row.Ratio;
ws.Cells[rowIndex, 4].Value = electorate;
ws.Cells[rowIndex, 5].Value = voteCount;
ws.Cells[rowIndex, 6].Value = totalVotes;
ws.Cells[rowIndex, 7].Value = electorate == 0 ? 0m : Round1((decimal)voteCount / electorate * 100m);
rowIndex++;
}
ws.Cells[rowIndex, 1].Value = "합계";
ws.Cells[rowIndex, 2].Value = rows.Sum(x => x.PollingPlaceCount);
ws.Cells[rowIndex, 3].Value = rows.Sum(x => x.Ratio);
ws.Cells[rowIndex, 4].Value = populationRows.Sum(x => x.ElectorateCount);
ws.Cells[rowIndex, 5].Value = populationRows.Sum(x => x.VoteCount);
ws.Cells[rowIndex, 6].Value = populationRows.Sum(x => x.TotalCandidateVoteCount);
ws.Cells[rowIndex, 7].Value = populationRows.Sum(x => x.ElectorateCount) == 0 ? 0m : Round1((decimal)populationRows.Sum(x => x.VoteCount) / populationRows.Sum(x => x.ElectorateCount) * 100m);
ApplyCommonFormatting(ws, 7);
SetNumberFormats(ws, 3, rowIndex, new[] { 2, 4, 5, 6 }, "#,##0");
SetNumberFormats(ws, 3, rowIndex, new[] { 3 }, "0.00000");
SetNumberFormats(ws, 3, rowIndex, new[] { 7 }, "0.0");
}
/// <summary>
/// 기준설정 Mode Target 시트를 작성합니다(군집별 타깃 비교 표).
/// </summary>
/// <param name="ws">대상 워크시트.</param>
/// <param name="clusterRows">군집 요약 행 목록.</param>
/// <param name="rows">모집단 행 목록.</param>
private static void WriteModeTargetSheet(ExcelWorksheet ws, List<ClusterSummaryRow> clusterRows, List<ExtractionRow> rows)
{
MergeAndSet(ws, 1, 1, 1, 6, "Target 층별 현황");
ws.Cells[2, 1].Value = "층";
ws.Cells[2, 2].Value = "총투표구수";
ws.Cells[2, 3].Value = "유권자수";
ws.Cells[2, 4].Value = "층의 유권자비율";
ws.Cells[2, 5].Value = "추출투표구수";
ws.Cells[2, 6].Value = "해당지역";
FillHeaderGray(ws, 1, 1, 2, 6);
int rowIndex = 3;
foreach (ClusterSummaryRow row in clusterRows.OrderBy(x => x.ClusterNo))
{
List<ExtractionRow> clusterPopulation = rows.Where(x => x.ClusterNo == row.ClusterNo).OrderBy(x => x.OriginalOrder).ToList();
string areas = string.Join(string.Empty, clusterPopulation.Where(x => x.IsAutoSelected || x.IsAdjustedSelected).Select(x => x.EupMyeonDong + "-" + x.PollingPlaceNo + "투, "));
ws.Cells[rowIndex, 1].Value = row.ClusterNo + " 층";
ws.Cells[rowIndex, 2].Value = row.PollingPlaceCount;
ws.Cells[rowIndex, 3].Value = null;
ws.Cells[rowIndex, 4].Value = row.Ratio;
ws.Cells[rowIndex, 5].Value = row.SampleCount;
ws.Cells[rowIndex, 6].Value = areas;
rowIndex++;
}
ws.Cells[rowIndex, 1].Value = "합계";
ws.Cells[rowIndex, 2].Value = clusterRows.Sum(x => x.PollingPlaceCount);
ws.Cells[rowIndex, 3].Value = 0;
ws.Cells[rowIndex, 4].Value = clusterRows.Sum(x => x.Ratio);
ws.Cells[rowIndex, 5].Value = clusterRows.Sum(x => x.SampleCount);
ApplyCommonFormatting(ws, 6);
SetNumberFormats(ws, 3, rowIndex, new[] { 2, 5 }, "#,##0");
SetNumberFormats(ws, 3, rowIndex, new[] { 4 }, "0.00000");
}
/// <summary>
/// 클러스터(층) 타이틀 텍스트를 생성합니다(표본 수/정렬/오프셋 등 메타 포함).
/// </summary>
/// <param name="result">실 추출 결과 메타.</param>
/// <param name="clusterNo">군집(층) 번호.</param>
/// <param name="sampleCount">해당 층의 표본 수.</param>
/// <returns>표시용 타이틀 문자열.</returns>
private static string BuildClusterTitle(RealExtractionResult result, int clusterNo, int sampleCount)
{
string allocationText = result.IsAutoAllocation ? "추출 투표구수 자동 지정" : "추출 투표구수 수동 지정";
string sortText = string.IsNullOrWhiteSpace(result.SortDisplayName) ? "투표인수" : result.SortDisplayName;
string directionText = result.SortDescending ? "내림차순" : "오름차순";
string offsetText = BuildOffsetTitle(result.OffsetDescription);
return string.Format("{0}, 득표율 소트 : {1} - {2}, {3}, 총 {4}개짜리 층중 {5} 번째 층 추출 투표구 수 {6}개(총 {7}개) 추출", allocationText, sortText, directionText, offsetText, result.ClusterMax, clusterNo, sampleCount, result.TotalSampleCount);
}
/// <summary>
/// 오프셋 설명 텍스트를 생성합니다.
/// </summary>
/// <param name="offsetDescription">사용자에게 표시할 오프셋 설명.</param>
/// <returns>표시용 오프셋 설명 문자열.</returns>
private static string BuildOffsetTitle(string offsetDescription)
{
if (string.IsNullOrWhiteSpace(offsetDescription))
{
return "추출위치 기본값";
}
string text = offsetDescription.Trim();
if (text.StartsWith("n - "))
{
return "추출위치에서 -" + text.Substring(4) + " 옵션";
}
if (text.StartsWith("n + "))
{
return "추출위치에서 +" + text.Substring(4) + " 옵션";
}
if (text == "n")
{
return "추출위치 기본값";
}
return text;
}
/// <summary>
/// 후보자 이름/득표키/비율키 목록을 최소 3개까지 보정합니다.
/// </summary>
/// <param name="candidateNames">후보자 표시명 목록(부족 시 기본값 채움).</param>
/// <param name="candidateVoteKeys">후보자 득표 키 목록(부족 시 기본값 채움).</param>
/// <param name="candidateRatioKeys">후보자 득표율 키 목록(부족 시 기본값 채움).</param>
private static void NormalizeCandidateLists(List<string> candidateNames, List<string> candidateVoteKeys, List<string> candidateRatioKeys)
{
while (candidateNames.Count < 3)
{
candidateNames.Add("후보" + (candidateNames.Count + 1));
}
while (candidateVoteKeys.Count < 3)
{
candidateVoteKeys.Add("cand_" + (candidateVoteKeys.Count + 1));
}
while (candidateRatioKeys.Count < 3)
{
candidateRatioKeys.Add("cand_ratio_" + (candidateRatioKeys.Count + 1));
}
}
/// <summary>
/// 읍면동 라벨을 생성합니다(시군구가 있으면 "시군구-읍면동").
/// </summary>
/// <param name="row">대상 행.</param>
/// <returns>표시용 읍면동 라벨.</returns>
private static string BuildTownLabel(ExtractionRow row)
{
return string.IsNullOrWhiteSpace(row.SiGunGu) ? row.EupMyeonDong : row.SiGunGu + "-" + row.EupMyeonDong;
}
/// <summary>
/// 추출/모집단 행에서 지정 후보의 득표수를 반환합니다.
/// </summary>
/// <param name="row">대상 행.</param>
/// <param name="candidateVoteKey">후보자 득표 키(예: cand_1).</param>
/// <returns>득표수. 키 없거나 null이면 0.</returns>
private static decimal GetVoteByKey(ExtractionRow row, string candidateVoteKey)
{
if (row == null || row.CandidateVotes == null || string.IsNullOrWhiteSpace(candidateVoteKey))
{
return 0m;
}
return row.CandidateVotes.ContainsKey(candidateVoteKey) ? row.CandidateVotes[candidateVoteKey] : 0m;
}
/// <summary>
/// 행에 저장된 후보 득표율(%)을 반환합니다. 없으면 0.
/// </summary>
/// <param name="row">대상 행.</param>
/// <param name="candidateVoteKey">후보자 득표 키(예: cand_1).</param>
/// <returns>저장된 득표율(%). 없으면 0.</returns>
private static decimal GetStoredRatioByKey(ExtractionRow row, string candidateVoteKey)
{
if (row == null || row.CandidateRatios == null || string.IsNullOrWhiteSpace(candidateVoteKey))
{
return 0m;
}
string ratioKey = candidateVoteKey.Replace("cand_", "cand_ratio_");
return row.CandidateRatios.ContainsKey(ratioKey) ? row.CandidateRatios[ratioKey] : 0m;
}
/// <summary>
/// 행 단위 표시 득표율(%)을 계산합니다. 저장된 비율이 있으면 그것을 우선 사용합니다.
/// </summary>
/// <param name="row">대상 행.</param>
/// <param name="candidateVoteKey">후보자 득표 키.</param>
/// <returns>표시용 득표율(%).</returns>
private static decimal ComputeDisplayedRowRatio(ExtractionRow row, string candidateVoteKey)
{
if (row == null || row.TotalCandidateVoteCount <= 0)
{
return 0m;
}
decimal storedRatio = GetStoredRatioByKey(row, candidateVoteKey);
if (storedRatio > 0m)
{
return Round1(storedRatio);
}
return Round1(GetVoteByKey(row, candidateVoteKey) / row.TotalCandidateVoteCount * 100m);
}
/// <summary>
/// 클러스터(그룹) 내 실제 득표율(%)을 계산합니다.
/// </summary>
/// <param name="rows">대상 행 목록.</param>
/// <param name="candidateVoteKey">후보자 득표 키.</param>
/// <returns>득표율(%), 분모가 0이면 0.</returns>
private static decimal ComputeClusterActualRatio(List<ExtractionRow> rows, string candidateVoteKey)
{
int totalVotes = rows.Sum(x => x.TotalCandidateVoteCount);
if (totalVotes <= 0)
{
return 0m;
}
decimal vote = rows.Sum(x => GetVoteByKey(x, candidateVoteKey));
return Round1(Round2(vote / totalVotes * 100m));
}
/// <summary>
/// 그룹(임의 묶음) 내 득표율(%)을 계산합니다.
/// </summary>
/// <param name="rows">대상 행 목록.</param>
/// <param name="candidateVoteKey">후보자 득표 키.</param>
/// <returns>득표율(%), 분모가 0이면 0.</returns>
private static decimal ComputeGroupRatio(List<ExtractionRow> rows, string candidateVoteKey)
{
int totalVotes = rows.Sum(x => x.TotalCandidateVoteCount);
if (totalVotes <= 0)
{
return 0m;
}
decimal vote = rows.Sum(x => GetVoteByKey(x, candidateVoteKey));
return Round1(vote / totalVotes * 100m);
}
/// <summary>
/// 소수점 첫째 자리에서 반올림(away from zero)합니다.
/// </summary>
/// <param name="value">반올림할 값.</param>
/// <returns>소수 첫째 자리 반올림 값.</returns>
private static decimal Round1(decimal value)
{
return Math.Round(value, 1, MidpointRounding.AwayFromZero);
}
/// <summary>
/// 소수점 둘째 자리에서 반올림(away from zero)합니다.
/// </summary>
/// <param name="value">반올림할 값.</param>
/// <returns>소수 둘째 자리 반올림 값.</returns>
private static decimal Round2(decimal value)
{
return Math.Round(value, 2, MidpointRounding.AwayFromZero);
}
private static void MergeAndSet(ExcelWorksheet ws, int fromRow, int fromCol, int toRow, int toCol, object value)
{
ws.Cells[fromRow, fromCol, toRow, toCol].Merge = true;
ws.Cells[fromRow, fromCol].Value = value;
}
private static void FillHeaderGray(ExcelWorksheet ws, int fromRow, int fromCol, int toRow, int toCol)
{
using (ExcelRange range = ws.Cells[fromRow, fromCol, toRow, toCol])
{
range.Style.Fill.PatternType = ExcelFillStyle.Solid;
range.Style.Fill.BackgroundColor.SetColor(Color.FromArgb(242, 242, 242));
range.Style.Font.Bold = true;
range.Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;
range.Style.VerticalAlignment = ExcelVerticalAlignment.Center;
range.Style.WrapText = true;
}
}
private static void ApplyCommonFormatting(ExcelWorksheet ws, int columnCount)
{
if (ws.Dimension == null)
{
return;
}
using (ExcelRange range = ws.Cells[1, 1, ws.Dimension.End.Row, columnCount])
{
range.Style.Font.Name = "맑은 고딕";
range.Style.Font.Size = 9;
range.Style.Border.Top.Style = ExcelBorderStyle.Thin;
range.Style.Border.Bottom.Style = ExcelBorderStyle.Thin;
range.Style.Border.Left.Style = ExcelBorderStyle.Thin;
range.Style.Border.Right.Style = ExcelBorderStyle.Thin;
range.Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;
range.Style.VerticalAlignment = ExcelVerticalAlignment.Center;
}
for (int i = 1; i <= columnCount; i++)
{
if (i == 1)
{
ws.Column(i).Width = 16;
}
else if (i <= 4)
{
ws.Column(i).Width = 14;
}
else if (i <= 7)
{
ws.Column(i).Width = 20;
}
else if (i == 15)
{
ws.Column(i).Width = 45;
}
else
{
ws.Column(i).Width = 12;
}
}
}
private static void SetNumberFormats(ExcelWorksheet ws, int fromRow, int toRow, IEnumerable<int> columns, string numberFormat)
{
foreach (int col in columns)
{
ws.Cells[fromRow, col, toRow, col].Style.Numberformat.Format = numberFormat;
}
}
}
}