[C#] 윈폼(Windows Form) DataGridView 이용하여 Excel에 Export 하는 방법


 

이번 포스팅에서는 윈폼 DataGridView 컨트롤에 있는 데이터들을 ExcelExport 하는 방법에 대해서 알려 드리도록 하겠습니다.

 

이 방법을 알게 되시면, 나중에 Excel에 데이터를 보내고 싶으실 때 유용하게 사용하실 수 있을 거라고 생각됩니다.

 

그럼 먼저 아래와 같이 윈도우 폼 프로젝트를 생성하여 주시고


1. Label, 2. Button, 3. DataGridView 컨트롤을 아래처럼 배치하여 주시기 바랍니다.


 


여기까지 하였다면 이제 본격적으로 코드를 작성할건데

 

그 전에, 저는 이전에 학생(Student) 테이블을 오라클에서 생성하여 데이터를 미리 넣어 놓았고, 해당 데이터를 DataGridView 컨트롤에 뿌려 주도록 하겠습니다.


 

   참고로 Database연동 하여 DataGridView 데이터 바인딩 하는 방법은 앞에서 이미 포스팅을 하였기 때문에 여기서는 해당 방법에 대해서는 생략 하도록 하겠습니다^^


 

혹시 모르시는 분들은 아래 링크를 참조하여 보고 따라 하시면 되겠습니다.


http://afsdzvcx123.tistory.com/148?category=784689

 

우선 코드를 작성하기 전 참조에 아래와 같이        

Microsoft.Office.Interop.Excel을 추가 시켜 주시기 바랍니다.


 


 

[Program.cs]


1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100

101

102

103

1

using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Linq;

using System.Text;

using System.Threading;

using System.Threading.Tasks;

using System.Windows.Forms;

 

namespace Test

{

    public partial class Form1 : Form

    {

        public Form1()

        {

            InitializeComponent();

            this.Load += Main_Load;

            this.btn_Export.Click += BTN_Excel_Export_Click;

        }

 

        private void Main_Load(object sender, EventArgs e)

        {

            try

            {

                Student_Data_View_Load();

            }

            catch (Exception ex)

            {

                MessageBox.Show(ex.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);

            }

        }

 

        /// <summary>

        /// Excel Export 버튼 

        /// </summary>

        /// <param name="sender"></param>

        /// <param name="e"></param>

        private void BTN_Excel_Export_Click(object sender ,EventArgs e)

        {

            ExportToExcel();

        }

 

        private static void ConnectToDB()

        {

 

            while (OracleDBManager.Instance.GetConnection() == false)

            {

                MessageBox.Show("Database Connected Fail...");

 

                return;

            }

 

            MessageBox.Show("Database Connected Success!!");

        }

 

        /// <summary>

        /// STUDENT 테이블에서 데이터 조회하여

        /// DataGridView 데이터 보여줌

        /// </summary>

        private void Student_Data_View_Load()

        {

            try

            {

                string query = @"SELECT * FROM STUDENT";

 

                DataSet ds = new System.Data.DataSet();

                OracleDBManager.Instance.ExecuteDsQuery(ds, query);

 

                DataTable dt = new DataTable();

                dt = ds.Tables[0].Clone(); //ds 저장되어 있는 Student 테이블 복사 저장

 

                DataRow Row = null;

 

                if (ds == null || ds.Tables.Count == 0 || ds.Tables[0].Rows.Count == 0)

                    return;

 

                for(int idx = 0; idx < ds.Tables[0].Rows.Count; idx++)

                {

                    Row = ds.Tables[0].Rows[idx];

                    dt.ImportRow(Row);

                }              

 

                //DataSet 저장되어 있는 데이터 불러오기

                dataGridView1.DataSource = ds.Tables[0];

 

            }

            catch (Exception ex)

            {

                MessageBox.Show(ex.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);

            }

        }

 

        /// <summary>

        /// Excel Export 해주는

        /// 메서드

        /// </summary>

        private void ExportToExcel()

        {

            bool IsExport = false;

 

            // Creating a Excel object.

            Microsoft.Office.Interop.Excel._Application excel = new Microsoft.Office.Interop.Excel.Application();

            Microsoft.Office.Interop.Excel._Workbook workbook = excel.Workbooks.Add(Type.Missing);

            Microsoft.Office.Interop.Excel._Worksheet worksheet = null;

 

            //DataGridView 불러온 Data 아무것도 없을 경우

            if (dataGridView1.Rows.Count == 0)

            {

                MessageBox.Show("Data does not exist.""Inform"

MessageBoxButtons.OK, MessageBoxIcon.Information);

                return;

            }

 

            try

            {

                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(ex.Message);

            }

        }

 

 

        private  SaveFileDialog GetExcelSave()

        {

            //Getting the location and file name of the excel to save from user.

            SaveFileDialog saveDialog = new SaveFileDialog();

            saveDialog.CheckPathExists = true;

            saveDialog.AddExtension = true;

            saveDialog.ValidateNames = true;

            saveDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);

 

            saveDialog.DefaultExt = ".xlsx";

            saveDialog.Filter = "Microsoft Excel Workbook (*.xls)|*.xlsx";

            saveDialog.FileName = "StudentData".ToString();

 

            return saveDialog;

        }

    }

}

 

Colored by Color Scripter

cs

 

위와 같이 코드를 작성하셨다면 이제 실제 프로그램을 실행 시켜 보도록 하겠습니다.

 

실행 결과 화면





▲ 위와 같이 Excel(엑셀)에 알맞게 Export가 된 것을 확인하실 수 있습니다.

 

감사합니다.^^




728x90

이 글을 공유하기

댓글

Designed by JB FACTORY