반응형
업무자동화가 점점 진행되고 있는 과정에서 업무 프로그램을 개발하다 보면 기존에 사용하고 있던 Excel 데이터를 프로그램에서 불러오거나 혹은 프로그램에서 작업한 데이터를 엑셀로 저장하는 경우가 발생합니다. 이번 포스팅에서는 C#에서 Excel을 불러오거나 데이터를 엑셀로 저장하는 방법에 대해 포스팅해 보도록 하겠습니다.
1. Visual Studio에서 화면디자인 하기
Visual Studio에서 프로젝트를 추가하고 아래와 같이 화면을 디자인합니다.
2. Microsoft.Office.Interop.Excel 참조 및 엑셀을 사용하기 위한 기초코딩
Microsoft.Office.Interop.Excel 참조하고 상단에 using을 사용하여 import 외부 dll파일을 사용할 수 있도록 추가해줍니다. 그리고 생성자 위 부분에 전역변수로 사용할 수 있도록 아래와 같이 코딩합니다.
3. 엑셀 가져오기 버튼 이벤트 생성
버튼을 더블클릭하여 이벤트를 생성하여 주고 openFileDialog의 이벤트에서 FileOk 이벤트도 추가해줍니다.
/// <summary>
/// 엑셀데이터 불러오기
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnGetExcelData_Click(object sender, EventArgs e)
{
openFileDialog1.ShowDialog();
}
/// <summary>
/// openFileDialog1에서 파일 선택 이벤트
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void openFileDialog1_FileOk(object sender, CancelEventArgs e)
{
string filePath = openFileDialog1.FileName;
string fileExtension = Path.GetExtension(filePath);
string header = "Yes"; //rbHeaderYes.Checked ? "Yes" : "No";
string connectionString = string.Empty;
string sheetName = string.Empty;
// 확장자로 구분하여 커넥션 스트링을 가져옮
switch (fileExtension)
{
case ".xls": //Excel 97-03
connectionString = string.Format(Excel03ConString, filePath, header);
break;
case ".xlsx": //Excel 07
connectionString = string.Format(Excel07ConString, filePath, header);
break;
}
// 첫 번째 시트의 이름을 가져옮
using (OleDbConnection con = new OleDbConnection(connectionString))
{
using (OleDbCommand cmd = new OleDbCommand())
{
cmd.Connection = con;
con.Open();
DataTable dtExcelSchema = con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
sheetName = dtExcelSchema.Rows[0]["TABLE_NAME"].ToString();
con.Close();
}
}
Console.WriteLine("sheetName = " + sheetName);
// 첫 번째 시트의 데이타를 읽어서 datagridview 에 보이게 함.
using (OleDbConnection con = new OleDbConnection(connectionString))
{
using (OleDbCommand cmd = new OleDbCommand())
{
using (OleDbDataAdapter oda = new OleDbDataAdapter())
{
DataTable dt = new DataTable();
cmd.CommandText = "SELECT * From [" + sheetName + "]";
cmd.Connection = con;
con.Open();
oda.SelectCommand = cmd;
oda.Fill(dt);
con.Close();
dataGridView1.DataSource = dt;
}
}
}
}
|
4. 엑셀 저장하기 버튼 이벤트 생성
해당 버튼을 더블클릭하여 이벤트를 생성합니다. 엑셀로 불러온 데이터를 저장하기 위해서는 엑셀이 설치되어 있어야 합니다.
/// <summary>
/// 엑셀데이터 저장하기
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnPutExcelData_Click(object sender, EventArgs e)
{
try
{
SaveFileDialog sfd = new SaveFileDialog();
sfd.Title = "Save as Excel File";
sfd.Filter = "Excel Files(2003)|*.xls|Excel Files(2007)|*.xlsx";
sfd.FileName = "사원명부 엑셀저장";
if (sfd.ShowDialog() == DialogResult.OK)
{
excelApp = new Excel.Application();
if (excelApp == null)
{
MessageBox.Show("엑셀이 설치되지 않았습니다");
return;
}
wb = excelApp.Workbooks.Add(true);
workSheet = wb.Worksheets.get_Item(1) as Excel._Worksheet;
workSheet.Name = "사원명부";
if (dataGridView1.Rows.Count == 0)
{
MessageBox.Show("출력할 데이터가 없습니다");
return;
}
// 헤더 출력
for (int i = 0; i < dataGridView1.Columns.Count; i++)
{
workSheet.Cells[1, i + 1] = dataGridView1.Columns[i].HeaderText;
}
//내용 출력
for (int r = 0; r < dataGridView1.Rows.Count; r++)
{
for (int i = 0; i < dataGridView1.Columns.Count; i++)
{
workSheet.Cells[r + 2, i + 1] = dataGridView1.Rows[r].Cells[i].Value;
}
}
// 엑셀 2003 으로만 저장이 됨
wb.SaveAs(sfd.FileName, Excel.XlFileFormat.xlWorkbookNormal, Type.Missing, Type.Missing, Type.Missing, Type.Missing,
Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
wb.Close(Type.Missing, Type.Missing, Type.Missing);
excelApp.Quit();
releaseObject(excelApp);
releaseObject(workSheet);
releaseObject(wb);
MessageBox.Show("작업이 완료되었습니다.");
}
}
catch(Exception Ex)
{
MessageBox.Show(Ex.Message);
}
}
/// <summary>
/// 메모리해제
/// </summary>
/// <param name="obj"></param>
private static void releaseObject(object obj)
{
try
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
obj = null;
}
catch (Exception e)
{
obj = null;
}
finally
{
GC.Collect();
}
}
|
5. 실행화면
프로젝트를 빌드하여 실행시킨 화면입니다.
여기까지 DataGridView에 Excel 불러오기 저장하기 포스팅을 마치도록 하겠습니다.
반응형
'개발 Recording > c#' 카테고리의 다른 글
[DB연동] C# 에서 MES 데이터베이스(Mysql) 연동 (0) | 2021.11.14 |
---|---|
[C#] "lc.exe"이(가) 종료되었습니다(코드:-1) 오류 해결 (0) | 2021.11.03 |