CAFE

25기 2조

[기술][2조 이후용]DB 데이터를 Excel로 저장

작성자25기 이후용|작성시간13.05.07|조회수777 목록 댓글 0

 

 

 

 

 

 

C# Excel

소요 시간 :

13/05/03 4시간

DB데이터를 GridView로 보여준 후 Excel로 저장

작성자 :

이후용

 

 

 

 

 

 

 

[실행 후 버튼 클릭시]

 

 

 

 

[저장 후 폴더 생김]

 

 

  

[ExcelDB내용 들어간 것 확인]

 

 

 

Form1.cs

using Excel = Microsoft.Office.Interop.Excel;

 

public Form1()

{

    InitializeComponent();

 

    string sqlstr = @"Data Source=BIT24\BIT58PC;Initial Catalog=ProjectA;User ID=sa;Password=1";

    SqlConnection conn = new SqlConnection(sqlstr);

    conn.Open();

    SqlDataAdapter sda = new SqlDataAdapter("select * from Environment", conn);

 

    DataSet ds = new DataSet("pTable");

    sda.Fill(ds, "Environment");

 

    dataGridView1.DataSource = ds.Tables["Environment"];

}

 

Microsoft.Office.Interop.Excel 라이브러리를 추가한다.(.NET부분에서 버전 12.0으로)

엑셀변환할 쓰이는 Microsoft.Office.Interop.Excel 매번 쓰기 번거로우므로 Excel 사용하자고 약속하자.

MS SQL 연결한 DataSet을이용하여 새로운 pTable 생성하여 MS SQL 만들어 놓은 Environment

테이블의 데이터들을 pTable 채운다. DataGridView 데이터들을 넣어 보여준다.

private void button1_Click(object sender, EventArgs e) // DataGridView Excel파일로 저장

{

    Excel.Application app;

    Excel._Workbook book;

    Excel.Workbooks books;

    Excel.Sheets sheets;

    Excel._Worksheet sheet;

    Excel.Range range;

    SaveFileDialog sfd = new SaveFileDialog();

    sfd.FileName = "practice";

    sfd.DefaultExt = "xls";

    sfd.Filter = "Excel files (*.xls)|*.xls";

    sfd.InitialDirectory = "Desktop\\";//"C:\\";

 

    DialogResult result = sfd.ShowDialog();

버튼을 하나 생성하여 Excel 데이터를 넣기 위한 위의 6가지를 선언한다.

저장할 사용자가 위치를 정할 있게 SaveFileDialog 생성해 주었다.

본인은 저장할 임의로 이름을 practice 하였고 excel파일이기 때문에 임의 확장자는

xls로정하였으며  파일형식으로 저장하는 필터는 위와 같이 적어주고 기본 저장위치는

 바탕화면으로 하였다. 그리고 저장 다이얼로그를 화면에 나타내준다.

if (result == DialogResult.OK)

    {

        int n = 0;

        object mtype = Type.Missing;

        string[] title = new string[dataGridView1.ColumnCount];

        string[] price = new string[dataGridView1.ColumnCount];

 

        for (int i = 0; i < dataGridView1.ColumnCount; i++)

        {

            title[i] = dataGridView1.Rows[0].Cells[i].OwningColumn.HeaderText.ToString();

*           n = i + 65;

            price[i] = Convert.ToString((char)n);

        }

 

        try

        {

            app = new Excel.Application();

            books = app.Workbooks;

            book = books.Add(Missing.Value);

            sheets = book.Worksheets;

            sheet = (Excel._Worksheet)sheets.get_Item(1);

 

            if (true)

            {

                for (int i = 0; i < dataGridView1.ColumnCount; i++)

                {

                   range = sheet.get_Range(price[i] + "1", Missing.Value);

                    range.set_Value(Missing.Value, title[i]);

                }

            }

 

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

            {

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

                {

 

                    range = sheet.get_Range(price[j] + Convert.ToString(i + 2), Missing.Value);

                    range.set_Value(Missing.Value, dataGridView1.Rows[i].Cells[j].Value.ToString());

                }

            }

            app.Visible = false;

            app.UserControl = false;

 

            book.SaveAs(@sfd.FileName, Excel.XlFileFormat.xlWorkbookNormal,

                mtype, mtype, mtype, mtype, Excel.XlSaveAsAccessMode.xlNoChange,

                mtype, mtype, mtype, mtype, mtype);

            book.Close(false, mtype, mtype);

            Cursor.Current = Cursors.Default;

 

            MessageBox.Show("저장됨.");

        }

        catch

        {

            MessageBox.Show("에러다.");

        }

    }

}

* 부분에 n=i+65라고 하였는데 65미만은 애러가 나며, i+66부터 수를 올려서 엑셀 저장된 파일을

보면 A열부터 나열되지 않고 그뒤로 나열된다. 그리고 97 다시 65 같은 위치로 나열되어

저장된다.

:: Excel 데이터가 들어가는 방법들을 공부하고 보게 된다면 쉽게 구현할 있을것이다.

* 참고사이트 : http://support.microsoft.com/kb/302084/kohttp://tysite.tistory.com/53

* 안된 부분 : Excel 구버전인 .xls로는 저장 후 볼 수 있지만

             신버전인 .xlsx로 저장 후에는 파일을 열 수 없다고 뜬다.(직접 확장자를 x로 바꾸어 주면된다)

 

다음검색
현재 게시글 추가 기능 열기

댓글

댓글 리스트
맨위로

카페 검색

카페 검색어 입력폼