반응형
아래 코드 주석 참조
Excel.Application excelApp = null;
Excel.Workbook wb = null;
Excel.Worksheet ws = null;
string path = Path.Combine(Environment.CurrentDirectory.ToString(), "output.xlsx");
try
{
excelApp = new Excel.Application();
//wb = excelApp.Workbooks.Open(path); // 기존 파일 읽어 올 때
wb = excelApp.Workbooks.Add(); // 신규 생성활 때
ws = wb.Worksheets.get_Item(1) as Excel.Worksheet;
// 저장하기 위한 데이터 크기 지정
int column = 8;
int row = priceList.Count;
//(중요) 지금은 저장할 행렬의 크기만큼 지정
Excel.Range rng = ws.Range[ws.Cells[1, 1], ws.Cells[row, column]];
// 저장할 행렬 생성
object[,] data = new object[row, column];
// 데이터 저장
for (int r = 0; r < row; r++)
{
for (int c = 0; c < column; c++)
{
data[r, 0] = priceList[r].xPos.ToString();
data[r, 1] = priceList[r].sPattern;
data[r, 2] = priceList[r].iType.ToString();
data[r, 3] = priceList[r].mPrice.date.ToString();
data[r, 4] = priceList[r].mPrice.o.ToString();
data[r, 5] = priceList[r].mPrice.h.ToString();
data[r, 6] = priceList[r].mPrice.l.ToString();
data[r, 7] = priceList[r].mPrice.c.ToString();
// data[r , c] = Data[r, c] 저장할 데이터
}
}
// 데이터 적용
rng.Value = data;
//wb.Save(); // 오픈된 파일저장
wb.SaveAs(path); // 새로운 파일에 저장
wb.Close();
excelApp.Quit();
}
catch (Exception ex)
{ throw ex; }
finally {
ReleaseExcelObject(ws);
ReleaseExcelObject(wb);
ReleaseExcelObject(excelApp);
}
해제 코드
private static void ReleaseExcelObject(object obj)
{
try {
if (obj != null) {
Marshal.ReleaseComObject(obj);
obj = null;
}
} catch (Exception ex) {
obj = null;
throw ex;
} finally {
GC.Collect(); }
}
반응형
'Development > Visual C#' 카테고리의 다른 글
[C#] RestFul API 서버 만들기 예제 (0) | 2023.07.06 |
---|---|
System.Runtime.InteropServices.COMException (0x80040154): 클래스가 등록되지 않았습니다. (예외가 발생한 HRESULT: 0x80040154 (REGDB_E_CLASSNOTREG)) (0) | 2023.07.06 |
[C#] EventHandler 이벤트 핸들러 만들기 (1) | 2022.09.21 |
[C#] Kiwoom 로그인 수동 제어 (0) | 2022.09.13 |
[C#] Thread 생성 하기 (0) | 2021.07.16 |
댓글