■ DataGridView 클래스 : 엑셀 내보내기

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

using System.Reflection;

using System.Windows.Forms;

 

using Excel = Microsoft.Office.Interop.Excel;

 

#region 엑셀 내보내기 - ExportToExcel(dataGridView)

 

/// <summary>

/// 엑셀 내보내기

/// </summary>

/// <param name="dataGridView">데이터 그리드 뷰</param>

public void ExportToExcel(DataGridView dataGridView)

{

    Excel.Application excelApplication;

    Excel._Workbook   workbook;

    Excel._Worksheet  worksheet;

 

    excelApplication = new Excel.Application();

 

    excelApplication.Visible = false;

 

    workbook  = excelApplication.Workbooks.Add(Missing.Value);

    worksheet = workbook.ActiveSheet as Excel._Worksheet;

 

    object[,] headerValueArray = new object[1, dataGridView.ColumnCount];

 

    for(int i = 0; i < dataGridView.Columns.Count; i++)

    {

        headerValueArray[0, i] = dataGridView.Columns[i].HeaderText;

    }

                 

    Excel.Range startHeaderCell = worksheet.Cells[1, 1                       ];

    Excel.Range endHeaderCell   = worksheet.Cells[1, dataGridView.ColumnCount];

 

    worksheet.get_Range(startHeaderCell as object, endHeaderCell as object).Font.Bold         = true;

    worksheet.get_Range(startHeaderCell as object, endHeaderCell as object).VerticalAlignment = Excel.XlVAlign.xlVAlignCenter;

 

    worksheet.get_Range(startHeaderCell as object, endHeaderCell as object).Value2 = headerValueArray;

 

    object[,] cellValueArray = new object[dataGridView.RowCount, dataGridView.ColumnCount];

 

    for(int i = 0; i < dataGridView.RowCount - 1; i++)

    {

        for(int j = 0; j < dataGridView.ColumnCount; j++)

        {

            if(dataGridView.Rows[i].Cells[j].ValueType.Name == "String")

            {

                cellValueArray[i, j] = "'" + dataGridView.Rows[i].Cells[j].Value.ToString();

            }

            else

            {

                cellValueArray[i, j] = dataGridView.Rows[i].Cells[j].Value;

            }

        }

    }

 

    Excel.Range startCell = worksheet.Cells[2                        , 1                       ];

    Excel.Range endCell   = worksheet.Cells[dataGridView.RowCount + 1, dataGridView.ColumnCount];

 

    worksheet.get_Range(startCell as object, endCell as object).Value2 = cellValueArray;

                 

    excelApplication.Visible = true;

 

    excelApplication.UserControl = true;

}

 

#endregion

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

※ Microsoft.Office.Interop.Excel.dll 참조를 설정한다.

Posted by 사용자 icodebroker
TAG

댓글을 달아 주세요