본문 바로가기
Development/Visual C#

[C#] Excel 생성/읽기 데이터 저장하기

by qWooWp 2022. 10. 5.
반응형

아래 코드 주석 참조 

 

 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(); } 
}
반응형

댓글