공학속으로/C#

c# DataGridView의 데이터를 엑셀파일로 저장하는 예제

더월드 2021. 12. 21.

C#에서 DataGridView의 데이터를 엑셀파일로 저장하는 예제

//--------------------------
// 엑셀 파일 저장
//--------------------------
private void ExportToExcel()
{
    bool IsExport = false;

    // Creating a Excel object.
    try
    {
        Excel._Application excel = new Excel.Application();
        Excel._Workbook workbook = excel.Workbooks.Add(Type.Missing);
        Excel._Worksheet worksheet = null;

        //DataGridView에 불러온 Data가 아무것도 없을 경우
        if (dataGridView1.Rows.Count == 0)
        {
            MessageBox.Show("Data does not exist.", "Inform", MessageBoxButtons.OK, MessageBoxIcon.Information);

            return;
        }

        //worksheet = workbook.ActiveSheet;
        worksheet = (Excel.Worksheet)workbook.ActiveSheet;

        int cellRowIndex = 1;
        int cellColumnIndex = 1;

        for (int col = 0; col < dataGridView1.Columns.Count; col++)
        {
            if (cellRowIndex == 1)
            {
                worksheet.Cells[cellRowIndex, cellColumnIndex] = dataGridView1.Columns[col].HeaderText;
            }
            cellColumnIndex++;
        }

        cellColumnIndex = 1;
        cellRowIndex++;
        for (int row = 0; row < dataGridView1.Rows.Count - 1; row++)
        {
            for (int col = 0; col < dataGridView1.Columns.Count; col++)
            {
                worksheet.Cells[cellRowIndex, cellColumnIndex] = dataGridView1.Rows[row].Cells[col].Value.ToString();
                cellColumnIndex++;
            }
            cellColumnIndex = 1;
            cellRowIndex++;
        }

        SaveFileDialog saveFileDialog = GetExcelSave();

        if (saveFileDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
        {
            workbook.SaveAs(saveFileDialog.FileName);
            MessageBox.Show("Export Successful!!!!!");
            IsExport = true;
        }

        //Export 성공 했으면 객체들 해제
        if (IsExport)
        {
            workbook.Close();
            excel.Quit();
            workbook = null;
            excel = null;
        }
    }
    catch (System.Exception ex)
    {
        MessageBox.Show(String.Format("엑셀이 설치되지 않았습니다. 저장할 수 없습니다. - {0}", ex.Message));
    }
}

댓글

💲 추천 글