티스토리 뷰
IT 이야기/프로그래밍
[C#] MDB(Access) 파일을 읽어 Excel에 넣고 Excel 실행 예제 [출처] MDB(Access) 파일을 읽어 Excel에 넣고 Excel 실행 예제
하늘과 나b 2011. 5. 31. 02:58student.mdb 파일은 Student라는 테이블이 있으며 그 내용은 다음과 같습니다.
id name addr tel
1 가길동 서울 11-2222
2 나기롱 울산 222-3333
3 다길동 부산 444-5555
이를 통해 만들어진 student.xls 파일은 다음과 같이 생겼습니다...
위의 mdb 파일과 내용이 같겠죠^^;;;
id name addr tel
1 가길동 서울 11-2222
2 나기롱 울산 222-3333
3 다길동 부산 444-5555
소스 코드는 다음과 같습니다.
---------------------------------------------------
using System;
using System.Drawing;
using System.Collections;
using System.Windows.Forms;
using System.Data;
using System.Data.OleDb;
//아래의 using 문이 가능할려면 프로젝트 --> 참조추가 --> com 탭에서 Microsofot Excel Object 10.0 또는 11.0(2003 버전) 추가
//using Excel = Microsoft.Office.Interop.Excel; //for Office 2003
using Excel;
namespace Exam
{
/// <summary>
/// Form1에 대한 요약 설명입니다.
/// </summary>
public class Form1 : System.Windows.Forms.Form
{
private System.Windows.Forms.Button button1;
/// <summary>
/// 필수 디자이너 변수입니다.
/// </summary>
private System.ComponentModel.Container components = null;
public Form1()
{
//
// Windows Form 디자이너 지원에 필요합니다.
//
InitializeComponent();
//
// TODO: InitializeComponent를 호출한 다음 생성자 코드를 추가합니다.
//
}
/// <summary>
/// 사용 중인 모든 리소스를 정리합니다.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if (components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
#region Windows Form 디자이너에서 생성한 코드
/// <summary>
/// 디자이너 지원에 필요한 메서드입니다.
/// 이 메서드의 내용을 코드 편집기로 수정하지 마십시오.
/// </summary>
private void InitializeComponent()
{
this.button1 = new System.Windows.Forms.Button();
this.SuspendLayout();
//
// button1
//
this.button1.Font = new System.Drawing.Font("굴림", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(129)));
this.button1.Location = new System.Drawing.Point(32, 16);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(208, 72);
this.button1.TabIndex = 0;
this.button1.Text = "MDB 파일을 읽어 Excel에 저장 후 Excel 실행";
this.button1.Click += new System.EventHandler(this.button1_Click);
//
// Form1
//
this.AutoScaleBaseSize = new System.Drawing.Size(6, 14);
this.ClientSize = new System.Drawing.Size(280, 126);
this.Controls.Add(this.button1);
this.Name = "Form1";
this.Text = "Form1";
this.ResumeLayout(false);
}
#endregion
/// <summary>
/// 해당 응용 프로그램의 주 진입점입니다.
/// </summary>
[STAThread]
static void Main()
{
System.Windows.Forms.Application.Run(new Form1());
}
private void button1_Click(object sender, System.EventArgs e)
{
OleDbConnection AdoConn = null;
OleDbConnection ExcelConn = null;
try
{
string strConn =@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=""D:\강의자료\울산\예제\C#\C#(2)\ADO\ExcelInsert-FileLoad\Exam\Exam\bin\Debug\student.mdb"";";
string ExcelCon=@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=""D:\강의자료\울산\예제\C#\C#(2)\ADO\ExcelInsert-FileLoad\Exam\Exam\bin\Debug\student.xls"";Extended Properties=""Excel 8.0;HDR=YES""" ;
AdoConn = new OleDbConnection (strConn);
AdoConn.Open();
string AdoSQL="Select id, name, addr, tel from student";
OleDbCommand Cmd = new OleDbCommand(AdoSQL, AdoConn);
OleDbDataReader reader=Cmd.ExecuteReader();
// 엑셀이 있는지 확인하여 없으면 만든다
// 필드을 확인후 없으면 만든다
ExcelConn=new OleDbConnection(ExcelCon);
ExcelConn.Open();
OleDbCommand ExcelCom;
while(reader.Read())
{
string ExcelSQL="INSERT INTO[sheet1$] (id, name, addr, tel) "
+ "VALUES('" + reader[0]+ "',"
+ "'"+ reader[1]+ "',"
+ "'"+reader[2]+ "',"
+ "'"+reader[3]+ "') ";
ExcelCom=new OleDbCommand(ExcelSQL,ExcelConn);
int nrow=ExcelCom.ExecuteNonQuery();
}
reader.Close();
ExcelConn.Close();
//엑셀화일열기 ------------------------------------------------------
//방법1
/*
Excel.Application App=new Excel.Application();
Excel.Workbook wk=App.Workbooks.Open(@"D:\강의자료\울산\예제\C#\C#(2)\ADO\ExcelInsert-FileLoad\Exam\Exam\bin\Debug\student.xls"
,Type.Missing, Type.Missing, Type.Missing, Type.Missing,
Type.Missing, Type.Missing, Type.Missing, Type.Missing,
Type.Missing, Type.Missing, Type.Missing, Type.Missing,
Type.Missing, Type.Missing);
App.Workbooks[1].Activate();
App.Visible=true;
App.UserControl=true;
*/
//방법2, 경로는 본인의 환경에 맞게 적절히 주세요....
System.Diagnostics.Process.Start("Excel",@"D:\강의자료\울산\예제\C#\C#(2)\ADO\ExcelInsert-FileLoad\Exam\Exam\bin\Debug\student.xls");
//마찬가지로 웹브라우저를 실행 하기 위해서는 아래와 같이 하면 됩니다.
System.Diagnostics.Process.Start("IEXPLORE.EXE", "www.oraclejava.co.kr");
}
catch(Exception ex)
{
MessageBox.Show(ex.ToString());
}
finally
{
AdoConn.Close();
ExcelConn.Close();
}
}
}
}
id name addr tel
1 가길동 서울 11-2222
2 나기롱 울산 222-3333
3 다길동 부산 444-5555
이를 통해 만들어진 student.xls 파일은 다음과 같이 생겼습니다...
위의 mdb 파일과 내용이 같겠죠^^;;;
id name addr tel
1 가길동 서울 11-2222
2 나기롱 울산 222-3333
3 다길동 부산 444-5555
소스 코드는 다음과 같습니다.
---------------------------------------------------
using System;
using System.Drawing;
using System.Collections;
using System.Windows.Forms;
using System.Data;
using System.Data.OleDb;
//아래의 using 문이 가능할려면 프로젝트 --> 참조추가 --> com 탭에서 Microsofot Excel Object 10.0 또는 11.0(2003 버전) 추가
//using Excel = Microsoft.Office.Interop.Excel; //for Office 2003
using Excel;
namespace Exam
{
/// <summary>
/// Form1에 대한 요약 설명입니다.
/// </summary>
public class Form1 : System.Windows.Forms.Form
{
private System.Windows.Forms.Button button1;
/// <summary>
/// 필수 디자이너 변수입니다.
/// </summary>
private System.ComponentModel.Container components = null;
public Form1()
{
//
// Windows Form 디자이너 지원에 필요합니다.
//
InitializeComponent();
//
// TODO: InitializeComponent를 호출한 다음 생성자 코드를 추가합니다.
//
}
/// <summary>
/// 사용 중인 모든 리소스를 정리합니다.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if (components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
#region Windows Form 디자이너에서 생성한 코드
/// <summary>
/// 디자이너 지원에 필요한 메서드입니다.
/// 이 메서드의 내용을 코드 편집기로 수정하지 마십시오.
/// </summary>
private void InitializeComponent()
{
this.button1 = new System.Windows.Forms.Button();
this.SuspendLayout();
//
// button1
//
this.button1.Font = new System.Drawing.Font("굴림", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(129)));
this.button1.Location = new System.Drawing.Point(32, 16);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(208, 72);
this.button1.TabIndex = 0;
this.button1.Text = "MDB 파일을 읽어 Excel에 저장 후 Excel 실행";
this.button1.Click += new System.EventHandler(this.button1_Click);
//
// Form1
//
this.AutoScaleBaseSize = new System.Drawing.Size(6, 14);
this.ClientSize = new System.Drawing.Size(280, 126);
this.Controls.Add(this.button1);
this.Name = "Form1";
this.Text = "Form1";
this.ResumeLayout(false);
}
#endregion
/// <summary>
/// 해당 응용 프로그램의 주 진입점입니다.
/// </summary>
[STAThread]
static void Main()
{
System.Windows.Forms.Application.Run(new Form1());
}
private void button1_Click(object sender, System.EventArgs e)
{
OleDbConnection AdoConn = null;
OleDbConnection ExcelConn = null;
try
{
string strConn =@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=""D:\강의자료\울산\예제\C#\C#(2)\ADO\ExcelInsert-FileLoad\Exam\Exam\bin\Debug\student.mdb"";";
string ExcelCon=@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=""D:\강의자료\울산\예제\C#\C#(2)\ADO\ExcelInsert-FileLoad\Exam\Exam\bin\Debug\student.xls"";Extended Properties=""Excel 8.0;HDR=YES""" ;
AdoConn = new OleDbConnection (strConn);
AdoConn.Open();
string AdoSQL="Select id, name, addr, tel from student";
OleDbCommand Cmd = new OleDbCommand(AdoSQL, AdoConn);
OleDbDataReader reader=Cmd.ExecuteReader();
// 엑셀이 있는지 확인하여 없으면 만든다
// 필드을 확인후 없으면 만든다
ExcelConn=new OleDbConnection(ExcelCon);
ExcelConn.Open();
OleDbCommand ExcelCom;
while(reader.Read())
{
string ExcelSQL="INSERT INTO[sheet1$] (id, name, addr, tel) "
+ "VALUES('" + reader[0]+ "',"
+ "'"+ reader[1]+ "',"
+ "'"+reader[2]+ "',"
+ "'"+reader[3]+ "') ";
ExcelCom=new OleDbCommand(ExcelSQL,ExcelConn);
int nrow=ExcelCom.ExecuteNonQuery();
}
reader.Close();
ExcelConn.Close();
//엑셀화일열기 ------------------------------------------------------
//방법1
/*
Excel.Application App=new Excel.Application();
Excel.Workbook wk=App.Workbooks.Open(@"D:\강의자료\울산\예제\C#\C#(2)\ADO\ExcelInsert-FileLoad\Exam\Exam\bin\Debug\student.xls"
,Type.Missing, Type.Missing, Type.Missing, Type.Missing,
Type.Missing, Type.Missing, Type.Missing, Type.Missing,
Type.Missing, Type.Missing, Type.Missing, Type.Missing,
Type.Missing, Type.Missing);
App.Workbooks[1].Activate();
App.Visible=true;
App.UserControl=true;
*/
//방법2, 경로는 본인의 환경에 맞게 적절히 주세요....
System.Diagnostics.Process.Start("Excel",@"D:\강의자료\울산\예제\C#\C#(2)\ADO\ExcelInsert-FileLoad\Exam\Exam\bin\Debug\student.xls");
//마찬가지로 웹브라우저를 실행 하기 위해서는 아래와 같이 하면 됩니다.
System.Diagnostics.Process.Start("IEXPLORE.EXE", "www.oraclejava.co.kr");
}
catch(Exception ex)
{
MessageBox.Show(ex.ToString());
}
finally
{
AdoConn.Close();
ExcelConn.Close();
}
}
}
}
'IT 이야기 > 프로그래밍' 카테고리의 다른 글
[HTML 쉽게 이해하기 강좌] 2단 레이아웃 한 방에 만들기 (4) | 2011.07.04 |
---|---|
[HTML 쉽게 이해하기 강좌 #3] HTML의 기본 태그에 대해 알아보기 (2) | 2011.06.30 |
[HTML 쉽게 이해하기 강좌 #2] - HTML 시작하기 (0) | 2011.06.30 |
[프로그래밍 사이트 추천] 웹에서도 프로그래밍 할 수 있다? 없다? 결론은 있다! (1) | 2011.06.23 |
[프로그래밍 Tip] 프로그램 소스코드를 공개하는 사이트 모음! (0) | 2011.06.01 |
[C#] 무료 기술 서적 - Inside C# (한글 번역본) 다운로드 (1) | 2011.05.31 |
[C#] DataGridView 쉽게 사용하기 - DataGridView컨트롤에 데이터를 삽입하는 예제 소스 (18) | 2011.05.22 |
[C#] C#에서 MS Access DB접속 방법 (0) | 2011.05.20 |
[JSP] Jakarta POI를 이용해서 엑셀(Excel)파일 다루는 방법 (2) | 2011.05.16 |
[자바스크립트] 즐겨찾기 소스 (0) | 2011.05.14 |
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday
링크
- W3Schools Online Web Tutorials
- 구차니의 잡동사니 모음
- [IT]블로거팁닷컴
- 비앤아이님의 블로그
- Blog Suspect
- 즐거운하루 blog
- zinicap의 검색엔진 마케팅(SEM)
- 머니야머니야님의 블로그
- [Friend] AtinStory
- [기타배우기]해브원 박스
- [웹표준] SINDB.com
- 해커 C 이야기
- [애드센스] 길라잡이
- 정순봉의 IT SCHOOL
- 씨디맨의 컴퓨터이야기
- 2proo Life Story
- 못된준코의 세상리뷰
- [IT강좌] 정보문화사
- IN 대전
- 에우르트는 나쁜남자 -_-
- 씬의 싱크탱크
- 엔돌슨의 IT이야기
- 진이늘이
- 'Cooltime'의 블로그
- 후이의 Tistory
- Soulstorage
- 앤드&엔드의 블로그
- June Blog
- 노지의 소박한 이야기
- gbWorld
- 인터넷 속 나의 생각
- HarshNix
- ART of WEB
- 녹두장군 - 상상을 현실로
TAG
- 모토로이
- 강좌
- 안드로이드 어플 추천
- 인터넷
- 소스
- 프로그래밍 문제
- C언어 소스
- MBTI 강좌
- 안드로이드 어플
- 강의
- JavaScript
- HTML
- MBTI
- 리뷰
- 프로그래밍
- 소스코드
- 성공
- 스마트폰
- 예제 소스
- MBTI 검사
- 효과음
- 인터넷 익스플로러
- MBTI 자료
- It
- C언어
- 안드로이드
- C
- MBTI 테스트
- C언어 문제
- php
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
글 보관함