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 { /// /// 실 추출 결과를 Excel 워크북(.xlsx)으로 내보내는 서비스입니다. /// public sealed class ExcelReportService { /// /// 실 추출 결과와 관련 시트를 포함한 Excel 워크북을 저장합니다. /// /// 저장할 파일 경로. /// 선거명 또는 연월. /// 시도명. /// 군집 요약 행 목록(모드 시트 등에 사용). /// 실 추출 결과 DTO. public void ExportRealExtractionWorkbook(string filePath, string electionName, string areaName, List 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 candidateNames = (result.CandidateNames ?? new List()).ToList(); List candidateVoteKeys = (result.CandidateVoteKeys ?? new List()).ToList(); List candidateRatioKeys = (result.CandidateRatioKeys ?? new List()).ToList(); NormalizeCandidateLists(candidateNames, candidateVoteKeys, candidateRatioKeys); WriteExtractedSheet(package.Workbook.Worksheets.Add(areaName + "-추출결과"), electionName, areaName, candidateNames, candidateVoteKeys, result.ExtractedRows ?? new List(), result.PopulationRows ?? new List(), result); WriteVerificationSummarySheet(package.Workbook.Worksheets.Add(areaName + "-자가 검증-요약분석"), electionName, areaName, candidateNames, result.VerificationRows ?? new List(), result.ClusterMax); WriteVerificationDetailSheet(package.Workbook.Worksheets.Add(areaName + "-자가 검증-세부분석"), electionName, areaName, candidateNames, candidateVoteKeys, result.ExtractedRows ?? new List(), result.VerificationRows ?? new List(), result.ClusterMax); WriteFinalStatusSheet(package.Workbook.Worksheets.Add(areaName + "-최종 투표소 추출현황"), electionName, areaName, candidateNames, candidateVoteKeys, result.PopulationRows ?? new List(), result.ClusterMax); WriteClusterListSheet(package.Workbook.Worksheets.Add(areaName + "-층별 시군구 리스트"), electionName, areaName, result.PopulationRows ?? new List()); WriteModeSheet(package.Workbook.Worksheets.Add(areaName + "-기준설정 Mode"), electionName, clusterRows ?? new List(), result.PopulationRows ?? new List()); WriteModeTargetSheet(package.Workbook.Worksheets.Add(areaName + "-기준설정 Mode Target"), clusterRows ?? new List(), result.PopulationRows ?? new List()); package.SaveAs(new FileInfo(filePath)); } } /// /// 추출 결과 시트를 작성합니다(클러스터별 표본과 모집단 요약 포함). /// /// 대상 워크시트. /// 선거명 또는 연월. /// 시도명. /// 후보자 표시명 목록(최소 3개로 보정됨). /// 후보자 득표 키 목록(최소 3개로 보정됨). /// 추출 표본 행 목록. /// 모집단 행 목록. /// 추출 실행 메타(정렬/오프셋 등). private static void WriteExtractedSheet(ExcelWorksheet ws, string electionName, string areaName, List candidateNames, List candidateVoteKeys, List rows, List populationRows, RealExtractionResult result) { int rowIndex = 1; foreach (IGrouping 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 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"); } /// /// 추출 결과 시트의 헤더(타이틀/열 병합/후보 라벨)를 설정합니다. /// /// 대상 워크시트. /// 헤더를 쓸 시작 행. /// 후보자 표시명 목록. /// 층(군집) 최대 개수. private static void SetExtractHeader(ExcelWorksheet ws, int rowIndex, List 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; } /// /// 자가 검증-요약분석 시트를 작성합니다(전체/층별 득표율 및 오차 요약). /// /// 대상 워크시트. /// 선거명 또는 연월. /// 시도명. /// 후보자 표시명 목록. /// 검증 요약 행 목록. /// 군집(층) 최대 개수. private static void WriteVerificationSummarySheet(ExcelWorksheet ws, string electionName, string areaName, List candidateNames, List 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"); } /// /// 자가 검증-세부분석 시트를 작성합니다(층/구간별 상세 지표 포함). /// /// 대상 워크시트. /// 선거명 또는 연월. /// 시도명. /// 후보자 표시명 목록. /// 후보자 득표 키 목록. /// 추출 표본 행 목록. /// 검증 요약 행 목록. /// 군집(층) 최대 개수. private static void WriteVerificationDetailSheet(ExcelWorksheet ws, string electionName, string areaName, List candidateNames, List candidateVoteKeys, List rows, List 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 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"); } /// /// 요약 행 데이터를 세부 형식과 동일하게 한 줄로 출력합니다. /// /// 대상 워크시트. /// 기록할 시작 행. /// 요약 데이터. /// 왼쪽 라벨. /// 오른쪽 라벨. /// 군집 내 오차 컬럼 포함 여부. 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; } } /// /// 최종 투표소 추출현황 시트를 작성합니다(모집단 내 각 행과 후보 득표수/비율 표시). /// /// 대상 워크시트. /// 선거명 또는 연월. /// 시도명. /// 후보자 표시명 목록. /// 후보자 득표 키 목록. /// 모집단 행 목록. /// 군집(층) 최대 개수. private static void WriteFinalStatusSheet(ExcelWorksheet ws, string electionName, string areaName, List candidateNames, List candidateVoteKeys, List 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 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"); } /// /// 층별 시군구 리스트 시트를 작성합니다(군집별로 읍면동 묶음 출력). /// /// 대상 워크시트. /// 선거명 또는 연월. /// 시도명. /// 모집단 행 목록. private static void WriteClusterListSheet(ExcelWorksheet ws, string electionName, string areaName, List 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); } /// /// 기준설정 Mode 시트를 작성합니다(군집 요약과 모집단 정보를 활용한 기준표). /// /// 대상 워크시트. /// 선거명 또는 연월. /// 군집 요약 행 목록. /// 모집단 행 목록. private static void WriteModeSheet(ExcelWorksheet ws, string electionName, List rows, List 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 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"); } /// /// 기준설정 Mode Target 시트를 작성합니다(군집별 타깃 비교 표). /// /// 대상 워크시트. /// 군집 요약 행 목록. /// 모집단 행 목록. private static void WriteModeTargetSheet(ExcelWorksheet ws, List clusterRows, List 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 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"); } /// /// 클러스터(층) 타이틀 텍스트를 생성합니다(표본 수/정렬/오프셋 등 메타 포함). /// /// 실 추출 결과 메타. /// 군집(층) 번호. /// 해당 층의 표본 수. /// 표시용 타이틀 문자열. 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); } /// /// 오프셋 설명 텍스트를 생성합니다. /// /// 사용자에게 표시할 오프셋 설명. /// 표시용 오프셋 설명 문자열. 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; } /// /// 후보자 이름/득표키/비율키 목록을 최소 3개까지 보정합니다. /// /// 후보자 표시명 목록(부족 시 기본값 채움). /// 후보자 득표 키 목록(부족 시 기본값 채움). /// 후보자 득표율 키 목록(부족 시 기본값 채움). private static void NormalizeCandidateLists(List candidateNames, List candidateVoteKeys, List 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)); } } /// /// 읍면동 라벨을 생성합니다(시군구가 있으면 "시군구-읍면동"). /// /// 대상 행. /// 표시용 읍면동 라벨. private static string BuildTownLabel(ExtractionRow row) { return string.IsNullOrWhiteSpace(row.SiGunGu) ? row.EupMyeonDong : row.SiGunGu + "-" + row.EupMyeonDong; } /// /// 추출/모집단 행에서 지정 후보의 득표수를 반환합니다. /// /// 대상 행. /// 후보자 득표 키(예: cand_1). /// 득표수. 키 없거나 null이면 0. 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; } /// /// 행에 저장된 후보 득표율(%)을 반환합니다. 없으면 0. /// /// 대상 행. /// 후보자 득표 키(예: cand_1). /// 저장된 득표율(%). 없으면 0. 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; } /// /// 행 단위 표시 득표율(%)을 계산합니다. 저장된 비율이 있으면 그것을 우선 사용합니다. /// /// 대상 행. /// 후보자 득표 키. /// 표시용 득표율(%). 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); } /// /// 클러스터(그룹) 내 실제 득표율(%)을 계산합니다. /// /// 대상 행 목록. /// 후보자 득표 키. /// 득표율(%), 분모가 0이면 0. private static decimal ComputeClusterActualRatio(List 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)); } /// /// 그룹(임의 묶음) 내 득표율(%)을 계산합니다. /// /// 대상 행 목록. /// 후보자 득표 키. /// 득표율(%), 분모가 0이면 0. private static decimal ComputeGroupRatio(List 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); } /// /// 소수점 첫째 자리에서 반올림(away from zero)합니다. /// /// 반올림할 값. /// 소수 첫째 자리 반올림 값. private static decimal Round1(decimal value) { return Math.Round(value, 1, MidpointRounding.AwayFromZero); } /// /// 소수점 둘째 자리에서 반올림(away from zero)합니다. /// /// 반올림할 값. /// 소수 둘째 자리 반올림 값. 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 columns, string numberFormat) { foreach (int col in columns) { ws.Cells[fromRow, col, toRow, col].Style.Numberformat.Format = numberFormat; } } } }