Dev/C#

C# interop.Excel 데이터 export

giftDev 2024. 6. 9. 22:33
반응형

      private void ExcelExport2()
    {
        Excel.Application excelApplication = null;
        Excel.Workbook excelWorkbook = null;
        Excel.Worksheet excelWorksheet = null;
        Excel.Range range = null;
  


        try
        {
            // Instantiate Excel and start a new workbook.
            string desktopPath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);  // 바탕화면 경로
            string path = Path.Combine(desktopPath, "Excel1.xlsx");                              // 엑셀 파일 저장 경로, 파일명
            excelApplication = new Excel.Application();                             // 엑셀 어플리케이션 생성
            excelWorkbook = excelApplication.Workbooks.Add();                            // 워크북 추가
            excelWorksheet = excelWorkbook.Worksheets.get_Item(1) as Excel.Worksheet; // 엑셀 첫번째 워크시트 가져오기


 

            excelApplication.ScreenUpdating = false;
            excelApplication.Calculation = Excel.XlCalculation.xlCalculationManual;



            // 컬럼 생성
            excelWorksheet.Cells[1, 1] = "1";
            excelWorksheet.Cells[1, 2] = "2";
            excelWorksheet.Cells[1, 3] = "3";
            excelWorksheet.Cells[1, 4] = "4";
            excelWorksheet.Cells[1, 5] = "5";
            excelWorksheet.Cells[1, 6] = "6";

            // 값 추가할 시작 범위 지정
            //Get the range where the starting cell has the address
            //m_sStartingCell and its dimensions are m_iNumRows x m_iNumCols.
            range = excelWorksheet.get_Range("A2", Missing.Value);


            //if (this.FillWithStrings.Checked == false)
            //{
            //Create an array.
            //double[,] saRet = new double[5, 5];

            //    //Fill the array.
            //    for (long iRow = 0; iRow < 5; iRow++)
            //    {
            //        for (long iCol = 0; iCol < 5; iCol++)
            //        {
            //            //Put a counter in the cell.
            //            saRet[iRow, iCol] = iRow * iCol;
            //        }
            //    }

            //    //Set the range value to the array.
            //    range.set_Value(Missing.Value, saRet);


            listView1.BeginUpdate();

            object[,] valueObject = new object[listView1.Items.Count, listView1.Items[0].SubItems.Count];
            range = range.get_Resize(listView1.Items.Count, listView1.Items[0].SubItems.Count);

            for (int iRow = 0; iRow < listView1.Items.Count; iRow++)
            {
                for (int iCol = 0; iCol < listView1.Items[0].SubItems.Count; iCol++)
                {
                    //Put a counter in the cell.
                    valueObject[iRow, iCol] = listView1.Items[iRow].SubItems[iCol].Text;
                }
            }
            //  excelWorksheet.Range.Value2 = new object[] { };
        
            listView1.EndUpdate();
            range.set_Value(Missing.Value, valueObject);
            excelWorksheet.Columns.AutoFit();                                    // 열 너비 자동 맞춤
            excelWorkbook.SaveAs(path, Excel.XlFileFormat.xlWorkbookDefault);    // 엑셀 파일 저장
            excelWorkbook.Close(true);
            excelApplication.Quit();
            //   }

            //else
            //{
            //    //Create an array.
            //    string[,] saRet = new string[5, 5];

            //    //Fill the array.
            //    for (long iRow = 0; iRow < 5; iRow++)
            //    {
            //        for (long iCol = 0; iCol < 5; iCol++)
            //        {
            //            //Put the row and column address in the cell.
            //            saRet[iRow, iCol] = iRow.ToString() + "|" + iCol.ToString();
            //        }
            //    }

            //    //Set the range value to the array.
            //    range.set_Value(Missing.Value, saRet);
            //}

            //Return control of Excel to the user.

        }
        catch (Exception theException)
        {
            string errorMessage;
            errorMessage = "Error: ";
            errorMessage = string.Concat(errorMessage, theException.Message);
            errorMessage = string.Concat(errorMessage, " Line: ");
            errorMessage = string.Concat(errorMessage, theException.Source);

            MessageBox.Show(errorMessage, "Error");
        }
        finally
        {
            ReleaseObject(range);

            ReleaseObject(excelWorksheet);
            ReleaseObject(excelWorkbook);
            ReleaseObject(excelApplication);
        }
    }

 

 

  private void ReleaseObject(object obj)
  {
      try
      {
          if (obj != null)
          {
              Marshal.ReleaseComObject(obj);  // 액셀 객체 해제
              obj = null;
          }
      }
      catch (Exception ex)
      {
          obj = null;
          throw ex;
      }
      finally
      {
          GC.Collect();   // 가비지 수집
      }
  }

 

 

반응형