309 lines
10 KiB
C#
309 lines
10 KiB
C#
using System;
|
|
using System.Diagnostics;
|
|
using System.IO;
|
|
using System.Runtime.InteropServices;
|
|
using Excel = Microsoft.Office.Interop.Excel;
|
|
|
|
namespace DwgExtractorManual.Models
|
|
{
|
|
/// <summary>
|
|
/// Excel COM 객체 관리 및 기본 작업을 담당하는 클래스
|
|
/// </summary>
|
|
internal class ExcelManager : IDisposable
|
|
{
|
|
public Excel.Application? ExcelApplication { get; private set; }
|
|
public Excel.Workbook? TitleBlockWorkbook { get; private set; }
|
|
public Excel.Workbook? MappingWorkbook { get; private set; }
|
|
|
|
public Excel.Worksheet? TitleBlockSheet { get; private set; }
|
|
public Excel.Worksheet? TextEntitiesSheet { get; private set; }
|
|
public Excel.Worksheet? MappingSheet { get; private set; }
|
|
|
|
/// <summary>
|
|
/// Excel 애플리케이션 및 워크시트 초기화
|
|
/// </summary>
|
|
public void InitializeExcel()
|
|
{
|
|
try
|
|
{
|
|
var excelApp = new Excel.Application();
|
|
ExcelApplication = excelApp;
|
|
ExcelApplication.Visible = false; // WPF에서는 숨김 처리
|
|
Excel.Workbook workbook = excelApp.Workbooks.Add();
|
|
TitleBlockWorkbook = workbook;
|
|
|
|
// Title Block Sheet 설정 (기본 Sheet1)
|
|
TitleBlockSheet = (Excel.Worksheet)workbook.Sheets[1];
|
|
TitleBlockSheet.Name = "Title Block";
|
|
SetupTitleBlockHeaders();
|
|
|
|
// Text Entities Sheet 추가
|
|
TextEntitiesSheet = (Excel.Worksheet)workbook.Sheets.Add();
|
|
TextEntitiesSheet.Name = "Text Entities";
|
|
SetupTextEntitiesHeaders();
|
|
|
|
// 매핑 데이터용 워크북 및 시트 생성
|
|
MappingWorkbook = excelApp.Workbooks.Add();
|
|
MappingSheet = (Excel.Worksheet)MappingWorkbook.Sheets[1];
|
|
MappingSheet.Name = "Mapping Data";
|
|
SetupMappingHeaders();
|
|
}
|
|
catch (System.Exception ex)
|
|
{
|
|
Debug.WriteLine($"Excel 초기화 중 오류 발생: {ex.Message}");
|
|
ReleaseExcelObjects();
|
|
throw;
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// 기존 Excel 파일을 열어 매핑 시트에 접근
|
|
/// </summary>
|
|
public bool OpenExistingFile(string excelFilePath)
|
|
{
|
|
try
|
|
{
|
|
if (!File.Exists(excelFilePath))
|
|
{
|
|
Debug.WriteLine($"? Excel 파일이 존재하지 않습니다: {excelFilePath}");
|
|
return false;
|
|
}
|
|
|
|
if (ExcelApplication == null)
|
|
{
|
|
ExcelApplication = new Excel.Application();
|
|
ExcelApplication.Visible = false;
|
|
}
|
|
|
|
MappingWorkbook = ExcelApplication.Workbooks.Open(excelFilePath);
|
|
MappingSheet = (Excel.Worksheet)MappingWorkbook.Sheets["Mapping Data"];
|
|
|
|
if (MappingSheet == null)
|
|
{
|
|
Debug.WriteLine("? 'Mapping Data' 시트를 찾을 수 없습니다.");
|
|
return false;
|
|
}
|
|
|
|
return true;
|
|
}
|
|
catch (System.Exception ex)
|
|
{
|
|
Debug.WriteLine($"? Excel 파일 열기 중 오류: {ex.Message}");
|
|
return false;
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// 새로운 워크북 생성 (Height 정렬용)
|
|
/// </summary>
|
|
public Excel.Workbook CreateNewWorkbook()
|
|
{
|
|
if (ExcelApplication == null)
|
|
{
|
|
ExcelApplication = new Excel.Application();
|
|
ExcelApplication.Visible = false;
|
|
}
|
|
return ExcelApplication.Workbooks.Add();
|
|
}
|
|
|
|
// Title Block 시트 헤더 설정
|
|
private void SetupTitleBlockHeaders()
|
|
{
|
|
if (TitleBlockSheet == null) return;
|
|
|
|
TitleBlockSheet.Cells[1, 1] = "Type"; // 예: AttributeReference, AttributeDefinition
|
|
TitleBlockSheet.Cells[1, 2] = "Name"; // BlockReference 이름 또는 BlockDefinition 이름
|
|
TitleBlockSheet.Cells[1, 3] = "Tag"; // Attribute Tag
|
|
TitleBlockSheet.Cells[1, 4] = "Prompt"; // Attribute Prompt
|
|
TitleBlockSheet.Cells[1, 5] = "Value"; // Attribute 값 (TextString)
|
|
TitleBlockSheet.Cells[1, 6] = "Path"; // 원본 DWG 파일 전체 경로
|
|
TitleBlockSheet.Cells[1, 7] = "FileName"; // 원본 DWG 파일 이름만
|
|
|
|
// 헤더 행 스타일
|
|
Excel.Range headerRange = TitleBlockSheet.Range["A1:G1"];
|
|
headerRange.Font.Bold = true;
|
|
headerRange.Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.LightBlue);
|
|
}
|
|
|
|
// Text Entities 시트 헤더 설정
|
|
private void SetupTextEntitiesHeaders()
|
|
{
|
|
if (TextEntitiesSheet == null) return;
|
|
|
|
TextEntitiesSheet.Cells[1, 1] = "Type"; // DBText, MText
|
|
TextEntitiesSheet.Cells[1, 2] = "Layer"; // Layer 이름
|
|
TextEntitiesSheet.Cells[1, 3] = "Text"; // 실제 텍스트 내용
|
|
TextEntitiesSheet.Cells[1, 4] = "Path"; // 원본 DWG 파일 전체 경로
|
|
TextEntitiesSheet.Cells[1, 5] = "FileName"; // 원본 DWG 파일 이름만
|
|
|
|
// 헤더 행 스타일
|
|
Excel.Range headerRange = TextEntitiesSheet.Range["A1:E1"];
|
|
headerRange.Font.Bold = true;
|
|
headerRange.Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.LightGreen);
|
|
}
|
|
|
|
// 매핑 데이터 시트 헤더 설정
|
|
private void SetupMappingHeaders()
|
|
{
|
|
if (MappingSheet == null) return;
|
|
|
|
MappingSheet.Cells[1, 1] = "FileName"; // 파일 이름
|
|
MappingSheet.Cells[1, 2] = "MapKey"; // 매핑 키
|
|
MappingSheet.Cells[1, 3] = "AILabel"; // AI 라벨
|
|
MappingSheet.Cells[1, 4] = "DwgTag"; // DWG Tag
|
|
MappingSheet.Cells[1, 5] = "Att_value"; // DWG 값
|
|
MappingSheet.Cells[1, 6] = "Pdf_value"; // PDF 값 (현재는 빈 값)
|
|
|
|
// 헤더 행 스타일
|
|
Excel.Range headerRange = MappingSheet.Range["A1:F1"];
|
|
headerRange.Font.Bold = true;
|
|
headerRange.Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.LightYellow);
|
|
}
|
|
|
|
/// <summary>
|
|
/// 워크북 저장
|
|
/// </summary>
|
|
public bool SaveWorkbook(Excel.Workbook? workbook = null)
|
|
{
|
|
try
|
|
{
|
|
if (workbook != null)
|
|
{
|
|
workbook.Save();
|
|
return true;
|
|
}
|
|
|
|
if (MappingWorkbook != null)
|
|
{
|
|
MappingWorkbook.Save();
|
|
return true;
|
|
}
|
|
|
|
if (TitleBlockWorkbook != null)
|
|
{
|
|
TitleBlockWorkbook.Save();
|
|
return true;
|
|
}
|
|
|
|
return false;
|
|
}
|
|
catch (System.Exception ex)
|
|
{
|
|
Debug.WriteLine($"? Excel 파일 저장 중 오류: {ex.Message}");
|
|
return false;
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// 워크북을 지정된 경로에 저장
|
|
/// </summary>
|
|
public void SaveWorkbookAs(Excel.Workbook? workbook, string savePath)
|
|
{
|
|
if (workbook == null) return;
|
|
|
|
string? directory = Path.GetDirectoryName(savePath);
|
|
if (!string.IsNullOrEmpty(directory) && !Directory.Exists(directory))
|
|
{
|
|
Directory.CreateDirectory(directory);
|
|
}
|
|
|
|
workbook.SaveAs(savePath,
|
|
FileFormat: Excel.XlFileFormat.xlOpenXMLWorkbook,
|
|
AccessMode: Excel.XlSaveAsAccessMode.xlNoChange);
|
|
}
|
|
|
|
/// <summary>
|
|
/// Excel 시트명으로 사용할 수 있는 유효한 이름을 생성합니다.
|
|
/// </summary>
|
|
public string GetValidSheetName(string originalName)
|
|
{
|
|
if (string.IsNullOrEmpty(originalName))
|
|
return "Sheet";
|
|
|
|
// Excel 시트명에서 허용되지 않는 문자 제거
|
|
string validName = originalName;
|
|
char[] invalidChars = { '\\', '/', '?', '*', '[', ']', ':' };
|
|
|
|
foreach (char c in invalidChars)
|
|
{
|
|
validName = validName.Replace(c, '_');
|
|
}
|
|
|
|
// 31자로 제한 (Excel 시트명 최대 길이)
|
|
if (validName.Length > 31)
|
|
{
|
|
validName = validName.Substring(0, 31);
|
|
}
|
|
|
|
return validName;
|
|
}
|
|
|
|
public void CloseWorkbooks()
|
|
{
|
|
if (TitleBlockWorkbook != null)
|
|
{
|
|
try { TitleBlockWorkbook.Close(false); }
|
|
catch { }
|
|
}
|
|
if (MappingWorkbook != null)
|
|
{
|
|
try { MappingWorkbook.Close(false); }
|
|
catch { }
|
|
}
|
|
if (ExcelApplication != null)
|
|
{
|
|
try { ExcelApplication.Quit(); }
|
|
catch { }
|
|
}
|
|
}
|
|
|
|
private void ReleaseExcelObjects()
|
|
{
|
|
ReleaseComObject(TitleBlockSheet);
|
|
ReleaseComObject(TextEntitiesSheet);
|
|
ReleaseComObject(MappingSheet);
|
|
ReleaseComObject(TitleBlockWorkbook);
|
|
ReleaseComObject(MappingWorkbook);
|
|
ReleaseComObject(ExcelApplication);
|
|
|
|
TitleBlockSheet = null;
|
|
TextEntitiesSheet = null;
|
|
MappingSheet = null;
|
|
TitleBlockWorkbook = null;
|
|
MappingWorkbook = null;
|
|
ExcelApplication = null;
|
|
}
|
|
|
|
private void ReleaseComObject(object? obj)
|
|
{
|
|
try
|
|
{
|
|
if (obj != null && Marshal.IsComObject(obj))
|
|
{
|
|
Marshal.ReleaseComObject(obj);
|
|
}
|
|
}
|
|
catch (System.Exception)
|
|
{
|
|
// 해제 중 오류 발생 시 무시
|
|
}
|
|
}
|
|
|
|
public void Dispose()
|
|
{
|
|
try
|
|
{
|
|
Debug.WriteLine("[DEBUG] ExcelManager Dispose 시작");
|
|
CloseWorkbooks();
|
|
ReleaseExcelObjects();
|
|
GC.Collect();
|
|
GC.WaitForPendingFinalizers();
|
|
Debug.WriteLine("[DEBUG] ExcelManager Dispose 완료");
|
|
}
|
|
catch (System.Exception ex)
|
|
{
|
|
Debug.WriteLine($"[DEBUG] ExcelManager Dispose 중 오류: {ex.Message}");
|
|
}
|
|
}
|
|
}
|
|
} |