Height sort, 한 파일에

This commit is contained in:
2025-07-28 11:20:21 +09:00
parent 9b94b59c49
commit 8bd5d9580c
3 changed files with 706 additions and 0 deletions

View File

@@ -1733,6 +1733,88 @@ namespace DwgExtractorManual
}
}
/// <summary>
/// DWG 추출 (Height 정렬) 버튼 클릭 이벤트
/// </summary>
private async void BtnDwgHeightSort_Click(object sender, RoutedEventArgs e)
{
try
{
// 경로 검증
string sourceFolder = txtSourceFolder.Text;
string resultFolder = txtResultFolder.Text;
if (string.IsNullOrWhiteSpace(sourceFolder) || !Directory.Exists(sourceFolder))
{
ShowMessageBox("올바른 소스 폴더를 선택해주세요.", "경로 오류", MessageBoxButton.OK, MessageBoxImage.Warning);
return;
}
if (string.IsNullOrWhiteSpace(resultFolder) || !Directory.Exists(resultFolder))
{
ShowMessageBox("올바른 결과 저장 폴더를 선택해주세요.", "경로 오류", MessageBoxButton.OK, MessageBoxImage.Warning);
return;
}
// 리프 폴더 찾기
var leafFolders = FindLeafFolders(sourceFolder);
if (leafFolders.Count == 0)
{
ShowMessageBox("처리할 리프 폴더가 없습니다.", "정보", MessageBoxButton.OK, MessageBoxImage.Information);
return;
}
LogMessage($"🔍 발견된 리프 폴더: {leafFolders.Count}개");
foreach (var folder in leafFolders)
{
LogMessage($" - {folder}");
}
// 사용자 확인
var result = ShowConfirmationDialog(
$"총 {leafFolders.Count}개의 리프 폴더에서 DWG Height 정렬 추출을 하시겠습니까?\n\n" +
"각 폴더마다 DWG 파일별로 시트가 생성되고, 텍스트 높이 순으로 정렬된 Excel 파일이 생성됩니다.",
"DWG Height 정렬 추출 확인");
if (result != MessageBoxResult.Yes)
{
return;
}
// UI 상태 변경
SetButtonsEnabled(false);
progressBar.Value = 0;
UpdateStatus("📏 DWG Height 정렬 추출 시작...");
// 자동 처리 모드 활성화
isAutoProcessing = true;
await ProcessLeafFoldersDwgHeightSort(leafFolders, resultFolder);
ShowMessageBox(
$"DWG Height 정렬 추출이 완료되었습니다!\n\n" +
$"처리된 폴더: {leafFolders.Count}개\n" +
$"결과 저장 위치: {resultFolder}",
"완료",
MessageBoxButton.OK,
MessageBoxImage.Information);
}
catch (Exception ex)
{
LogMessage($"❌ DWG Height 정렬 추출 중 오류: {ex.Message}");
ShowMessageBox($"DWG Height 정렬 추출 중 오류가 발생했습니다:\n{ex.Message}", "오류", MessageBoxButton.OK, MessageBoxImage.Error);
}
finally
{
SetButtonsEnabled(true);
progressBar.Value = 0;
UpdateStatus("✅ 준비");
// 자동 처리 모드 비활성화
isAutoProcessing = false;
}
}
/// <summary>
/// 폴더에서 리프 폴더들(하위 폴더가 없는 폴더)을 재귀적으로 찾습니다.
/// </summary>
@@ -1935,6 +2017,114 @@ namespace DwgExtractorManual
UpdateStatus("✅ DWG 전용 추출 완료");
}
/// <summary>
/// DWG Height 정렬 처리를 위한 리프 폴더 처리
/// </summary>
/// <param name="leafFolders">처리할 리프 폴더 목록</param>
/// <param name="resultBaseFolder">결과 저장 기본 폴더</param>
private async Task ProcessLeafFoldersDwgHeightSort(List<string> leafFolders, string resultBaseFolder)
{
int totalFolders = leafFolders.Count;
LogMessage($"📏 DWG Height 정렬 추출 시작: {totalFolders}개 폴더");
try
{
// 모든 폴더의 DWG 파일을 수집
var allDwgFiles = new List<(string filePath, string folderName)>();
for (int i = 0; i < leafFolders.Count; i++)
{
string leafFolder = leafFolders[i];
progressBar.Value = (double)(i + 1) / totalFolders * 50; // 첫 50%는 파일 수집용
LogMessage($"📁 [{i + 1}/{totalFolders}] 폴더 스캔 중: {leafFolder}");
var dwgFiles = Directory.GetFiles(leafFolder, "*.dwg", SearchOption.TopDirectoryOnly);
string folderName = Path.GetFileName(leafFolder);
foreach (var dwgFile in dwgFiles)
{
allDwgFiles.Add((dwgFile, folderName));
}
LogMessage($"📊 [{i + 1}/{totalFolders}] 발견된 DWG 파일: {dwgFiles.Length}개");
// UI 응답성을 위한 양보
await Task.Yield();
}
LogMessage($"📊 총 발견된 DWG 파일: {allDwgFiles.Count}개");
if (allDwgFiles.Count > 0)
{
// 단일 Excel 파일에 모든 DWG 파일 처리
LogMessage("📏 단일 Height 정렬 Excel 파일 생성 중...");
await ProcessAllFilesDwgHeightSort(allDwgFiles, resultBaseFolder);
LogMessage("✅ Height 정렬 Excel 파일 생성 완료");
}
else
{
LogMessage("⚠️ 처리할 DWG 파일이 없습니다.");
}
progressBar.Value = 100;
}
catch (Exception ex)
{
LogMessage($"❌ DWG Height 정렬 추출 중 오류: {ex.Message}");
throw;
}
LogMessage($"🎉 DWG Height 정렬 추출 완료! 총 {totalFolders}개 폴더 처리됨");
UpdateStatus("✅ DWG Height 정렬 추출 완료");
}
/// <summary>
/// 모든 DWG 파일을 단일 Excel 파일에서 Height 정렬하여 처리합니다.
/// </summary>
/// <param name="allDwgFiles">모든 DWG 파일 정보 (파일경로, 폴더명)</param>
/// <param name="resultFolder">결과 폴더</param>
private async Task ProcessAllFilesDwgHeightSort(List<(string filePath, string folderName)> allDwgFiles, string resultFolder)
{
ExportExcel exportExcel = null;
try
{
LogMessage($"📊 총 DWG 파일 수: {allDwgFiles.Count}개");
LogMessage($"📋 출력 모드: Excel (Height 정렬)");
LogMessage($"💾 결과 폴더: {resultFolder}");
LogMessage("📊 Excel Height 정렬 내보내기 모드로 시작합니다...");
LogMessage("📝 Excel 애플리케이션을 초기화합니다...");
exportExcel = new ExportExcel();
// UI 응답성을 위한 양보
await Task.Yield();
// Height 정렬된 Excel 파일 생성
LogMessage("📏 Height 정렬 Excel 파일 생성 중...");
// 단일 타임스탬프로 파일명 생성
string timestamp = DateTime.Now.ToString("yyyyMMdd_HHmmss");
string savePath = Path.Combine(resultFolder, $"{timestamp}_AllDWG_HeightSorted.xlsx");
exportExcel.ExportAllDwgToExcelHeightSorted(allDwgFiles, savePath);
LogMessage("✅ Height 정렬 Excel 파일 생성 완료");
LogMessage($"📁 저장된 파일: {Path.GetFileName(savePath)}");
}
catch (Exception ex)
{
LogMessage($"❌ DWG Height 정렬 처리 중 치명적 오류: {ex.Message}");
throw;
}
finally
{
exportExcel?.Dispose();
exportExcel = null;
}
}
/// <summary>
/// 지정된 폴더에서 DWG 파일들만 처리합니다.
/// </summary>
@@ -2044,6 +2234,104 @@ namespace DwgExtractorManual
}
}
/// <summary>
/// 지정된 폴더에서 DWG 파일들을 Height 정렬하여 처리합니다.
/// </summary>
/// <param name="sourceFolderPath">처리할 폴더 경로</param>
private async Task ProcessFilesDwgHeightSort(string sourceFolderPath)
{
ExportExcel exportExcel = null;
try
{
string resultFolder = txtResultFolder.Text;
if (!Directory.Exists(sourceFolderPath))
{
LogMessage($"❌ 소스 폴더가 존재하지 않습니다: {sourceFolderPath}");
return;
}
var dwgFiles = Directory.GetFiles(sourceFolderPath, "*.dwg", SearchOption.TopDirectoryOnly);
if (dwgFiles.Length == 0)
{
LogMessage($"📄 처리할 DWG 파일이 없습니다: {sourceFolderPath}");
return;
}
LogMessage($"📊 처리할 DWG 파일 수: {dwgFiles.Length}개");
LogMessage($"📋 출력 모드: Excel (Height 정렬)");
LogMessage($"📂 소스 폴더: {sourceFolderPath}");
LogMessage($"💾 결과 폴더: {resultFolder}");
LogMessage("📊 Excel Height 정렬 내보내기 모드로 시작합니다...");
LogMessage("📝 Excel 애플리케이션을 초기화합니다...");
exportExcel = new ExportExcel();
// UI 응답성을 위한 양보
await Task.Yield();
// Height 정렬된 Excel 파일 생성
LogMessage("📏 Height 정렬 Excel 파일 생성 중...");
exportExcel.ExportDwgToExcelHeightSorted(dwgFiles, resultFolder);
LogMessage("✅ Height 정렬 Excel 파일 생성 완료");
}
catch (Exception ex)
{
LogMessage($"❌ DWG Height 정렬 처리 중 치명적 오류: {ex.Message}");
throw;
}
finally
{
exportExcel?.Dispose();
exportExcel = null;
}
}
/// <summary>
/// DWG Height 정렬 Excel 파일을 목표 경로로 이름 변경
/// </summary>
/// <param name="resultFolder">결과 폴더</param>
/// <param name="leafFolderPath">리프 폴더 경로</param>
private async Task RenameDwgHeightSortExcelFile(string resultFolder, string leafFolderPath)
{
try
{
// 최신 *_HeightSorted.xlsx 파일 찾기
var excelFiles = Directory.GetFiles(resultFolder, "*_HeightSorted.xlsx")
.Where(f => !Path.GetFileName(f).StartsWith("~$"))
.OrderByDescending(f => File.GetCreationTime(f))
.ToList();
if (excelFiles.Any())
{
string latestFile = excelFiles.First();
// 리프 폴더 경로를 기반으로 파일명 생성
string relativePath = Path.GetRelativePath(txtSourceFolder.Text, leafFolderPath);
string safePath = relativePath.Replace('\\', '_').Replace('/', '_').Replace(':', '_');
string targetFileName = $"{safePath}_HeightSorted.xlsx";
string targetPath = Path.Combine(resultFolder, targetFileName);
// 목표 파일이 이미 존재하면 삭제
if (File.Exists(targetPath))
{
File.Delete(targetPath);
}
// 파일 이름 변경
File.Move(latestFile, targetPath);
LogMessage($"📋 Height 정렬 Excel 파일 이름 변경됨: {targetFileName}");
}
}
catch (Exception ex)
{
LogMessage($"⚠️ Height 정렬 Excel 파일 이름 변경 실패: {ex.Message}");
}
}
/// <summary>
/// 최신 Excel 파일을 목표 경로로 이름 변경
/// </summary>