첨부 실행 코드는 나눔고딕코딩 폰트를 사용합니다.
본 블로그는 광고를 포함하고 있습니다.
광고 클릭에서 발생하는 수익금은 모두 블로그 콘텐츠 향상을 위해 쓰여집니다.

728x90
반응형
728x170
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 파일을 참조한다.

728x90
반응형
그리드형
Posted by 사용자 icodebroker
TAG , ,

댓글을 달아 주세요