diff --git a/Keps.WinForms/Docs/투표구 추출 프로그램(keps) 분석.xlsx b/Keps.WinForms/Docs/투표구 추출 프로그램(keps) 분석.xlsx index 368ac1f..a9dbbae 100644 Binary files a/Keps.WinForms/Docs/투표구 추출 프로그램(keps) 분석.xlsx and b/Keps.WinForms/Docs/투표구 추출 프로그램(keps) 분석.xlsx differ diff --git a/Keps.WinForms/Forms/DataInputForm.Designer.cs b/Keps.WinForms/Forms/DataInputForm.Designer.cs index dda32e8..65216a7 100644 --- a/Keps.WinForms/Forms/DataInputForm.Designer.cs +++ b/Keps.WinForms/Forms/DataInputForm.Designer.cs @@ -8,13 +8,13 @@ namespace Keps.WinForms.Forms private System.Windows.Forms.Label _lblElection; private System.Windows.Forms.Label _lblFolder; private System.Windows.Forms.ComboBox _cmbElection; - private System.Windows.Forms.TextBox _txtFolder; + private System.Windows.Forms.TextBox _txtFile; private System.Windows.Forms.Button _btnFolder; private System.Windows.Forms.Button _btnImportReal; private System.Windows.Forms.ProgressBar _progress; private System.Windows.Forms.Label _lblMain; private System.Windows.Forms.Label _lblDetail; - private System.Windows.Forms.FolderBrowserDialog _folderDialog; + private System.Windows.Forms.OpenFileDialog _fileDialog; protected override void Dispose(bool disposing) { @@ -35,14 +35,14 @@ namespace Keps.WinForms.Forms this._lblElection = new System.Windows.Forms.Label(); this._cmbElection = new System.Windows.Forms.ComboBox(); this._lblFolder = new System.Windows.Forms.Label(); - this._txtFolder = new System.Windows.Forms.TextBox(); + this._txtFile = new System.Windows.Forms.TextBox(); this._btnFolder = new System.Windows.Forms.Button(); this._progress = new System.Windows.Forms.ProgressBar(); this._lblMain = new System.Windows.Forms.Label(); this._lblDetail = new System.Windows.Forms.Label(); this._buttonPanel = new System.Windows.Forms.FlowLayoutPanel(); this._btnImportReal = new System.Windows.Forms.Button(); - this._folderDialog = new System.Windows.Forms.FolderBrowserDialog(); + this._fileDialog = new System.Windows.Forms.OpenFileDialog(); this._layout.SuspendLayout(); this._buttonPanel.SuspendLayout(); this.SuspendLayout(); @@ -56,7 +56,7 @@ namespace Keps.WinForms.Forms this._layout.Controls.Add(this._lblElection, 0, 0); this._layout.Controls.Add(this._cmbElection, 1, 0); this._layout.Controls.Add(this._lblFolder, 0, 1); - this._layout.Controls.Add(this._txtFolder, 1, 1); + this._layout.Controls.Add(this._txtFile, 1, 1); this._layout.Controls.Add(this._btnFolder, 2, 1); this._layout.Controls.Add(this._progress, 0, 2); this._layout.Controls.Add(this._lblMain, 0, 3); @@ -102,16 +102,16 @@ namespace Keps.WinForms.Forms this._lblFolder.Name = "_lblFolder"; this._lblFolder.Size = new System.Drawing.Size(57, 12); this._lblFolder.TabIndex = 2; - this._lblFolder.Text = "엑셀 폴더"; + this._lblFolder.Text = "엑셀 파일"; // - // _txtFolder + // _txtFile // - this._txtFolder.Dock = System.Windows.Forms.DockStyle.Fill; - this._txtFolder.Location = new System.Drawing.Point(135, 41); - this._txtFolder.Name = "_txtFolder"; - this._txtFolder.ReadOnly = true; - this._txtFolder.Size = new System.Drawing.Size(670, 21); - this._txtFolder.TabIndex = 3; + this._txtFile.Dock = System.Windows.Forms.DockStyle.Fill; + this._txtFile.Location = new System.Drawing.Point(135, 41); + this._txtFile.Name = "_txtFile"; + this._txtFile.ReadOnly = true; + this._txtFile.Size = new System.Drawing.Size(670, 21); + this._txtFile.TabIndex = 3; // // _btnFolder // @@ -120,10 +120,15 @@ namespace Keps.WinForms.Forms this._btnFolder.Name = "_btnFolder"; this._btnFolder.Size = new System.Drawing.Size(100, 25); this._btnFolder.TabIndex = 4; - this._btnFolder.Text = "폴더 선택"; + this._btnFolder.Text = "파일 선택"; this._btnFolder.UseVisualStyleBackColor = true; this._btnFolder.Click += new System.EventHandler(this.BtnFolder_Click); // + // _fileDialog + // + this._fileDialog.Filter = "Excel 파일 (*.xlsx;*.xlsm)|*.xlsx;*.xlsm|모든 파일 (*.*)|*.*"; + this._fileDialog.Title = "엑셀 파일 선택"; + // // _progress // this._layout.SetColumnSpan(this._progress, 3); diff --git a/Keps.WinForms/Forms/DataInputForm.cs b/Keps.WinForms/Forms/DataInputForm.cs index 2532957..c528425 100644 --- a/Keps.WinForms/Forms/DataInputForm.cs +++ b/Keps.WinForms/Forms/DataInputForm.cs @@ -55,20 +55,20 @@ namespace Keps.WinForms.Forms private void BtnFolder_Click(object sender, EventArgs e) { - // 초기 디렉터리는 _txtFolder의 값(폴더이거나 파일이면 그 폴더) 또는 _appBasePath + // 초기 디렉터리는 _txtFile의 값(폴더이거나 파일이면 그 폴더) 또는 _appBasePath string initialDir = _appBasePath; - if (!string.IsNullOrWhiteSpace(_txtFolder.Text)) + if (!string.IsNullOrWhiteSpace(_txtFile.Text)) { try { - if (Directory.Exists(_txtFolder.Text)) + if (Directory.Exists(_txtFile.Text)) { - initialDir = _txtFolder.Text; + initialDir = _txtFile.Text; } else { - var dir = Path.GetDirectoryName(_txtFolder.Text); + var dir = Path.GetDirectoryName(_txtFile.Text); if (!string.IsNullOrWhiteSpace(dir) && Directory.Exists(dir)) initialDir = dir; } @@ -79,12 +79,12 @@ namespace Keps.WinForms.Forms } } - // FolderBrowserDialog는 SelectedPath로 초기 경로를 설정 - _folderDialog.SelectedPath = initialDir; + _fileDialog.InitialDirectory = initialDir; + _fileDialog.FileName = string.Empty; - if (_folderDialog.ShowDialog(this) == DialogResult.OK) + if (_fileDialog.ShowDialog(this) == DialogResult.OK) { - _txtFolder.Text = _folderDialog.SelectedPath; + _txtFile.Text = _fileDialog.FileName; } } @@ -102,13 +102,13 @@ namespace Keps.WinForms.Forms return; } - if (string.IsNullOrWhiteSpace(_txtFolder.Text) || !Directory.Exists(_txtFolder.Text)) + if (string.IsNullOrWhiteSpace(_txtFile.Text) || !File.Exists(_txtFile.Text)) { - MessageBox.Show(this, "엑셀 폴더를 선택하세요.", "확인", MessageBoxButtons.OK, MessageBoxIcon.Warning); + MessageBox.Show(this, "엑셀 파일을 선택하세요.", "확인", MessageBoxButtons.OK, MessageBoxIcon.Warning); return; } - string folderPath = _txtFolder.Text; + string filePath = _txtFile.Text; string electionName = _cmbElection.SelectedItem.ToString(); ToggleState(false); @@ -125,7 +125,7 @@ namespace Keps.WinForms.Forms { await Task.Run(() => { - _excelImportService.Import(folderPath, electionName, ImportMode.Real, progress); + _excelImportService.Import(filePath, electionName, ImportMode.Real, progress); }); _lblMain.Text = "완료"; diff --git a/Keps.WinForms/Forms/DataInputForm.resx b/Keps.WinForms/Forms/DataInputForm.resx index 9389daa..49b5701 100644 --- a/Keps.WinForms/Forms/DataInputForm.resx +++ b/Keps.WinForms/Forms/DataInputForm.resx @@ -117,7 +117,7 @@ System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - + 17, 17 - \ No newline at end of file + diff --git a/Keps.WinForms/Forms/RealExtractionForm.cs b/Keps.WinForms/Forms/RealExtractionForm.cs index 86ec185..9fd3588 100644 --- a/Keps.WinForms/Forms/RealExtractionForm.cs +++ b/Keps.WinForms/Forms/RealExtractionForm.cs @@ -82,7 +82,8 @@ namespace Keps.WinForms.Forms _numTotalSamples.Minimum = 1; _numTotalSamples.Maximum = 5000; - _numTotalSamples.Value = 123; + _numTotalSamples.Value = 1; + _numTotalSamples.Text = string.Empty; _numOffsetValue.Minimum = 0; _numOffsetValue.Maximum = 100; _preparedContext = null; @@ -181,10 +182,11 @@ namespace Keps.WinForms.Forms string election = _cmbElection.SelectedItem.ToString(); string area = _cmbArea.SelectedItem.ToString(); int clusterMax = Convert.ToInt32(_cmbClusterMax.SelectedItem); + int totalSamples = GetTotalSamples(); RealScenarioContext context = _samplingService.LoadRealScenario(election, area, clusterMax); _preparedContext = context; - _autoRows = new BindingList(_samplingService.AllocateAutoSampleCounts(context.AutoRows, Convert.ToInt32(_numTotalSamples.Value))); + _autoRows = new BindingList(_samplingService.AllocateAutoSampleCounts(context.AutoRows, totalSamples)); _manualRows = new BindingList(context.ManualRows.Select(CloneRow).ToList()); for (int i = 0; i < _manualRows.Count && i < _autoRows.Count; i++) { @@ -265,7 +267,13 @@ namespace Keps.WinForms.Forms if (_rdoAuto.Checked) { - _autoRows = new BindingList(_samplingService.AllocateAutoSampleCounts(_preparedContext.AutoRows, Convert.ToInt32(_numTotalSamples.Value))); + int totalSamples; + if (!TryGetTotalSamples(out totalSamples)) + { + return; + } + + _autoRows = new BindingList(_samplingService.AllocateAutoSampleCounts(_preparedContext.AutoRows, totalSamples)); if (_manualRows == null || _manualRows.Count != _autoRows.Count) { @@ -391,9 +399,37 @@ namespace Keps.WinForms.Forms MessageBox.Show(this, "군집수를 선택하세요.", "확인", MessageBoxButtons.OK, MessageBoxIcon.Warning); return false; } + if (!TryGetTotalSamples(out _)) + { + MessageBox.Show(this, "총 표본 수를 입력하세요.", "확인", MessageBoxButtons.OK, MessageBoxIcon.Warning); + _numTotalSamples.Focus(); + return false; + } return true; } + private int GetTotalSamples() + { + int totalSamples; + if (!TryGetTotalSamples(out totalSamples)) + { + throw new InvalidOperationException("총 표본 수를 입력하세요."); + } + return totalSamples; + } + + private bool TryGetTotalSamples(out int totalSamples) + { + totalSamples = 0; + if (string.IsNullOrWhiteSpace(_numTotalSamples.Text)) + { + return false; + } + + totalSamples = Convert.ToInt32(_numTotalSamples.Value); + return totalSamples >= _numTotalSamples.Minimum && totalSamples <= _numTotalSamples.Maximum; + } + private List GetWorkingRows() { return (_rdoAuto.Checked ? _autoRows : _manualRows).Select(CloneRow).ToList(); diff --git a/Keps.WinForms/Services/ExcelImportService.cs b/Keps.WinForms/Services/ExcelImportService.cs index 98bdc3b..3a52456 100644 --- a/Keps.WinForms/Services/ExcelImportService.cs +++ b/Keps.WinForms/Services/ExcelImportService.cs @@ -51,29 +51,29 @@ namespace Keps.WinForms.Services /// /// 지정한 폴더의 Excel 파일(.xlsx/.xlsm)을 읽어 실데이터를 DB에 적재합니다. /// - /// Excel 파일들이 위치한 폴더 경로. + /// 읽어들일 Excel 파일 경로. /// 적재 대상 선거 연월(예: "201804"). /// 적재 모드(현재 Real만 지원). /// 진행 상황을 보고받을 프로그레스 리스너. - /// 폴더가 없거나 지원 확장자가 없을 때 발생. + /// 파일이 없거나 지원 확장자가 아닐 때 발생. /// 미지원 모드일 때 발생. - public void Import(string folderPath, string electionYear, ImportMode mode, IProgress progress) + public void Import(string filePath, string electionYear, ImportMode mode, IProgress progress) { - if (string.IsNullOrWhiteSpace(folderPath) || !Directory.Exists(folderPath)) + if (string.IsNullOrWhiteSpace(filePath) || !File.Exists(filePath)) { - throw new InvalidOperationException("유효한 폴더를 선택하세요."); + throw new InvalidOperationException("유효한 Excel 파일을 선택하세요."); } - List files = [.. Directory.GetFiles(folderPath, "*.xlsx")]; - - if (files.Count == 0) + string extension = Path.GetExtension(filePath); + if (string.Equals(extension, ".xls", StringComparison.OrdinalIgnoreCase)) { - if (Directory.GetFiles(folderPath, "*.xls").Length > 0) - { - throw new InvalidOperationException("현재 버전은 EPPlus 4.5.3.3 기준으로 작성되어 .xlsx/.xlsm만 지원합니다. 기존 .xls 파일은 .xlsx로 변환 후 다시 시도하세요."); - } + throw new InvalidOperationException("현재 버전은 EPPlus 4.5.3.3 기준으로 작성되어 .xlsx/.xlsm만 지원합니다. 기존 .xls 파일은 .xlsx로 변환 후 다시 시도하세요."); + } - throw new InvalidOperationException("선택한 폴더에 지원되는 Excel 파일(.xlsx/.xlsm)이 없습니다."); + if (!string.Equals(extension, ".xlsx", StringComparison.OrdinalIgnoreCase) + && !string.Equals(extension, ".xlsm", StringComparison.OrdinalIgnoreCase)) + { + throw new InvalidOperationException("지원되는 Excel 파일(.xlsx/.xlsm)을 선택하세요."); } progress.Report(new ImportProgress(5, "기존 데이터 정리")); @@ -88,14 +88,13 @@ namespace Keps.WinForms.Services throw new NotSupportedException("시뮬레이션 엑셀 적재는 지원하지 않습니다."); } - string firstFile = files[0]; - progress.Report(new ImportProgress(10, Path.GetFileName(firstFile) + " 열기")); + progress.Report(new ImportProgress(10, Path.GetFileName(filePath) + " 열기")); List candidateNames = new List(); using (ExcelEpplusReader reader = new ExcelEpplusReader()) { - reader.Open(firstFile); + reader.Open(filePath); List sheets = new List(reader.ReadSheets()); for (int sheetIndex = 0; sheetIndex < sheets.Count; sheetIndex++) @@ -153,14 +152,20 @@ namespace Keps.WinForms.Services int totalColumn = sheet.FindHeaderColumn("계", 128); if (voteColumn <= 0 || totalColumn <= 0 || totalColumn <= voteColumn) { - return; + throw new InvalidOperationException( + string.Format( + "Excel 시트 '{0}'에서 필수 헤더를 찾을 수 없습니다. '투표수'와 '계' 헤더를 확인하세요.", + sheet.Name)); } int candidateStartColumn = voteColumn + 1; int candidateEndColumn = totalColumn - 1; if (candidateEndColumn < candidateStartColumn) { - return; + throw new InvalidOperationException( + string.Format( + "Excel 시트 '{0}'에서 후보자 득표 컬럼을 찾을 수 없습니다. '투표수'와 '계' 사이에 후보자 컬럼이 있는지 확인하세요.", + sheet.Name)); } if (candidateNames.Count == 0) @@ -207,10 +212,11 @@ namespace Keps.WinForms.Services candidateNo++; } - string buildingName = LegacyValueHelper.CleanString(sheet.GetValue(row, totalColumn + 2)).Replace("'", "'"); - string address1 = LegacyValueHelper.CleanString(sheet.GetValue(row, totalColumn + 3)).Replace("'", "'"); - string note = LegacyValueHelper.CleanString(sheet.GetValue(row, totalColumn + 4)); - string duplicateFlag = LegacyValueHelper.CleanString(sheet.GetValue(row, totalColumn + 5)); + string buildingName = LegacyValueHelper.CleanString(sheet.GetValue(row, totalColumn + 3)).Replace("'", "'"); + string address1 = LegacyValueHelper.CleanString(sheet.GetValue(row, totalColumn + 4)).Replace("'", "'"); + string note = LegacyValueHelper.CleanString(sheet.GetValue(row, totalColumn + 5)); + string duplicateFlag = LegacyValueHelper.CleanString(sheet.GetValue(row, totalColumn + 6)); + string areaDetail = LegacyValueHelper.CleanString(sheet.GetValue(row, totalColumn + 8)); string candJson = JsonHelper.Serialize(cand); string candRatioJson = JsonHelper.Serialize(candRatio); @@ -244,7 +250,7 @@ namespace Keps.WinForms.Services command.Parameters.Add(new SqlParameter("@candRatio", SqlDbType.VarChar, -1) { Value = candRatioJson ?? string.Empty }); command.Parameters.Add(new SqlParameter("@totalCandidateVoteCount", SqlDbType.Int) { Value = totalCandidateVotes }); command.Parameters.Add(new SqlParameter("@duplicateFlag", SqlDbType.VarChar, 50) { Value = duplicateFlag ?? string.Empty }); - command.Parameters.Add(new SqlParameter("@areaDetail", SqlDbType.VarChar, 50) { Value = string.Empty }); + command.Parameters.Add(new SqlParameter("@areaDetail", SqlDbType.VarChar, 50) { Value = areaDetail ?? string.Empty }); command.Parameters.Add(new SqlParameter("@buildingName", SqlDbType.VarChar, 500) { Value = buildingName ?? string.Empty }); command.Parameters.Add(new SqlParameter("@address1", SqlDbType.VarChar, 500) { Value = address1 ?? string.Empty }); command.Parameters.Add(new SqlParameter("@note", SqlDbType.VarChar, 200) { Value = note ?? string.Empty }); @@ -315,7 +321,7 @@ namespace Keps.WinForms.Services for (int i = 0; i < candidateNames.Count; i++) { - using (SqlCommand insertCommand = new SqlCommand("INSERT INTO cand_name(ele_ym, cand_no, cand_name) VALUES(@eleYm, @candNo, @candName)", connection)) + using (SqlCommand insertCommand = new SqlCommand("INSERT INTO cand_name(ele_ym, title, cand_no, cand_name, 당이름) VALUES(@eleYm, @eleYm, @candNo, @candName, @candName)", connection)) { insertCommand.Parameters.AddWithValue("@eleYm", electionYear); insertCommand.Parameters.AddWithValue("@candNo", (i + 1).ToString()); diff --git a/Keps.WinForms/Services/LegacySqlCatalog.cs b/Keps.WinForms/Services/LegacySqlCatalog.cs index 87babe2..0b376ba 100644 --- a/Keps.WinForms/Services/LegacySqlCatalog.cs +++ b/Keps.WinForms/Services/LegacySqlCatalog.cs @@ -10,7 +10,7 @@ namespace Keps.WinForms.Services /// 활성화된 선거 연월 목록 조회. public const string ElectionYears = "SELECT ele_ym FROM elections WHERE flag = '1' ORDER BY ele_ym DESC"; /// 실 데이터에 존재하는 선거명 목록. - public const string DistinctRealElections = "SELECT 선거명 FROM poll_data GROUP BY 선거명 ORDER BY 선거명"; + public const string DistinctRealElections = "SELECT 선거명 FROM poll_data a inner join elections b on a.ele_ym = b.ele_ym GROUP BY 선거명, a.ele_ym ORDER BY a.ele_ym desc"; /// 특정 선거명에 대한 시도명 목록. public const string DistinctRealAreas = "SELECT 시도명 FROM poll_data WHERE 선거명 = @electionName GROUP BY 시도명 ORDER BY 시도명"; /// 특정 선거/지역에 대한 군집 최대값 목록.