C,C#

C# winform 엑셀파일 특정값 가져와서 txt파일로 만들기(1)

kingsgirl 2023. 8. 16. 18:13
728x90

오류 CS0246
NuGet패키지에 Microsoft.Office.Interop.Excel 설치 했는데도

CS0246 "Excel"형식 또는 네임스페이스이름을 차즐수 없다고 뜨는 오류

해결 
using = Microsoft.Office.Interop.Excel;

변경 후

using Excel = Microsoft.Office.Interop.Excel;

 

-------------------------------------
  

Marshal.ReleaseComObject(workbook);
  //COM개체 참조카운트 감소시켜 메모리 해제 . 메모리누수 방지(엑셀프로세스죽이기)


 if(openfd.ShowDialog() == CommonFileDialogResult.Ok) 




 string selectedFolder = opendlg.FileName;
 //opendlg.FileName : 선택한 파일의 경로를 반환

 

 

메모  끝

------------------------------------------------------------------------------------------

코드 

    internal static class Program
    {
        /// <summary>
        /// 해당 애플리케이션의 주 진입점입니다.
        /// </summary>
        /// 
    
        
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            
            
            //Application.Run(new Form1());

            //파일 오픈 창 생성 및 설정
            CommonOpenFileDialog opendlg = new CommonOpenFileDialog();
            opendlg.IsFolderPicker = true;

            //다이얼로그 타이틀설정
            opendlg.Title = "파일 선택";
            opendlg.Multiselect = true;


            string[] pathFiles = null;
            if(opendlg.ShowDialog() == CommonFileDialogResult.Ok) 
            {
                pathFiles = opendlg.FileNames.ToArray();
                string selectedFolder = opendlg.FileName;
                //opendlg.FileName : 선택한 파일의 경로를 반환

                string[] excelFiles = Directory.GetFiles(selectedFolder, "*.xlsx");
                //excelFiles : 선택한 폴더 내 모든 엑셀파일 경로 


                //// if 문 선택한 파일들의 경로(pathFiles)를 이용하여 추가 작업을 수행할 수 있음
                
                // 선택한 폴더내 모든 엑셀파일에 대해 순차적으로 함수 호출 
                foreach (string filepath in excelFiles)
                //excelFiles 반복하면서 루프 내부 코드 실행
                //filepath : excelFiles 중 하나의 파일 엑셀경로
                {
                    ProcessExcelFile(filepath);
                    //현재 엑셀 파일 경로가 인자로써 ProcessExcelFile 함수 호출
                }

            }
  
            else
            { 
                return;
            }
        }


        static void ProcessExcelFile(string filepath)
        {
            Excel.Application excelApp = new Excel.Application();
            //excelApp으로 어플리케이션 조작
            Excel.Workbook workbook = null;

            try
            {
                workbook = excelApp.Workbooks.Open(filepath);

                foreach (Excel.Worksheet worksheet in workbook.Sheets)
                //workbook.Sheets : 엑셀파일의 모든 시트
                //각 시트 Excel.Worksheet 개체를 worksheet 변수에 할당

                {
                    ProcessWorksheet(worksheet);
                    //호출
                }
            }

            catch (Exception ex)
            {
                Console.WriteLine("Error :" +ex.Message);
            }
            finally
            //메모리누수 방지 및 excel프로세스 정상종료, 무조건 실행 
            {
                // workbook?.Close(false);
                //null이 아닐경우 에만 메서드 호출 " ?. " 연산자 , false : 저장하지않고닫음
                //Marshal.ReleaseComObject(workbook);
                //COM개체 참조카운트 감소시켜 메모리 해제 . 메모리누수 방지(엑셀프로세스죽이기)
            }

        }
   
        static void ProcessWorksheet(Excel.Worksheet worksheet)
         //현재 시트에 대한 작업 
        {
            try
            {

                int[] startRows = { 3 };//시작행번호

                int[] columnNumbers = { 2, 2, 6 }; //열 번호들


                string txtFilePath = Path.ChangeExtension(worksheet.Parent.FullName + "_" + worksheet.Name, "txt");

                using (StreamWriter writer = new StreamWriter(txtFilePath))
                {
                    for (int i = 0; i < startRows.Length; i++)
                    {
                        int startRow = startRows[i];
                        //startRows의 i번째를 startRow로 저장
                        int column = columnNumbers[i % columnNumbers.Length];
                        //열 번호 순환

                        for (int j = 0; j < 3; j++)
                        {
                            int row = startRow + (j * 7);
                            Console.WriteLine("row = startRow + (j * 7) 줄 Error :" + row);

                            //행 번호 계산

                            Excel.Range cell = worksheet.Cells[row, column];
                            string cellValue = cell.Value != null ? cell.Value.ToString() : "";

                            if (j < 2)
                            //마지막 값이 아니라면 탭문자 추가하여 값 구분
                            {
                                writer.Write("\t");
                            }

                        }

                        //다음 시작행번호
                        startRow += 7;

                        //마지막 값이 아니라면 줄바꿈 문자 추가하여 다음행으로 이동
                        if (i < startRows.Length - 1)
                        {
                            writer.WriteLine();
                        }




                    }
                }

            }
            catch (Exception ex) 
            
            {
                Console.WriteLine("Error :" + ex.Message + "ProcessWorksheet함수오류");

            }


        }


    }

-----------------------------------------------------------------------------------------------------------------------------

오류 

콘솔창에 

Error :파일 형식 또는 파일 확장명이 잘못되어 '~$*****.xlsx' 파일을 열 수 없습니다. 파일이 손상되지 않았는지,  파일 확장명이 파일 형식과 일치하는지 확인하십시오.

라고 뜨고 엄청 빠르게 for (int j = 0; j < 3; j++) 이 for문 안에 있는 
                            Console.WriteLine("row = startRow + (j * 7) 줄 Error :" + row); 이 메시지가 뜨고  종료됨 

728x90