Application/C# (WinForm)
[C# WinForm] 엑셀 파일 사용하기 2 (Excel)
devsalix
2024. 11. 14. 11:06
728x90
https://devsalix.tistory.com/76
[C# WinForm] 엑셀 파일 사용 하기 (Excel)
C#에서 OleDb와 DataTable을 사용해 Excel 파일을 접근하여 사용할 수 있습니다 우선 Excel 클래스로는 using System; using System.Data; using System.Data.OleDb; using System.Windows.Forms; public class CExcel { private OleDbConnectio
devsalix.tistory.com
이전 엑셀 파일 사용하기에 이어 두 번째 사용하는 방법에 대해 소개해 드리겠습니다
이전에는 엑셀을 DB화 하여 사용했다면 이번에는 다이렉트 접속으로 사용하는 방법에 대해 설명해 드리겠습니다
- 클래스 영역
using Excel = Microsoft.Office.Interop.Excel;
public class MainClass
{
private Excel.Application m_AppExcel = null;
public Excel.Worksheet OpenExcel(string sPath, int iSheet)
{
CloseExcel();
try
{
m_AppExcel = new Excel.Application();
Excel.Workbook wb;
wb = m_AppExcel.Workbooks.Open(sPath);
return (Excel.Worksheet)wb.Worksheets.Item[iSheet];
}
catch (Exception ex)
{
CloseExcel();
MessageBox.Show("Excel 파일 열기 실패\n\n" + ex.Message);
return null;
//throw ex;
}
}
public void CloseExcel()
{
try
{
if (m_AppExcel != null)
{
m_AppExcel.Quit();
Marshal.ReleaseComObject(m_AppExcel);
m_AppExcel = null;
}
}
catch (Exception ex)
{
m_AppExcel = null;
throw ex;
}
finally
{
GC.Collect();
}
}
public bool SaveExcel()
{
if (m_AppExcel == null) return false;
try
{
for(int iCnt = 0; iCnt < m_AppExcel.Workbooks.Count; iCnt++)
{
m_AppExcel.Workbooks[iCnt + 1].Save();
}
return true;
}
catch { }
return false;
}
}
- Excel 파일 사용
using Excel = Microsoft.Office.Interop.Excel;
private void UseExcel(string sPathExcel)
{
string sData;
Excel.Worksheet ws;
ws = m_MainClass.OpenExcel(sPathExcel, 1);
if (ws == null)
{
// Excel 열기 실패
return;
}
//A1 데이터 읽기
sData = (ws.Cells[1, 1] as Excel.Range).Value2.ToString();
//A1 데이터 쓰기
(ws.Cells[1, 1] as Excel.Range).Value2 = "쓰기 테스트";
m_MainModule.SaveExcel();
m_MainClass.CloseExcel();
}
제 글이 도움이 되셨다면 댓글 & 공감 부탁드려요 😀
728x90
반응형