using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.InteropServices; using System.Text; using System.Threading.Tasks; using Excel = Microsoft.Office.Interop.Excel; using System.Reflection; namespace NewsCrawler { public class ExcelHandler { bool m_bAvailable = false; string m_strFileName = ""; string m_strToday = DateTime.Now.ToString("yyyy-MM-dd"); Excel.Application m_App = null; public ExcelHandler(string strFileName) { m_App = new Excel.Application(); if(m_App == null) { Util.Log(Util.LOG_TYPE.ERROR, "엑셀이 설치되지 않음"); m_bAvailable = false; return; } m_strFileName = strFileName; } ~ExcelHandler() { Marshal.ReleaseComObject(m_App); } public bool IsAvailable() { return m_bAvailable; } private void Create() { Excel._Workbook Workbook = m_App.Workbooks.Add(Missing.Value); Excel._Worksheet Worksheet = Workbook.ActiveSheet; Worksheet.Cells[1, 1] = "날짜"; Worksheet.Cells[1, 2] = "기사 시간"; Worksheet.Cells[1, 3] = "받은 시간"; Worksheet.Cells[1, 4] = "출처"; Worksheet.Cells[1, 5] = "제목"; Worksheet.Cells[1, 6] = "요청 시간"; Worksheet.Cells[1, 7] = "시가"; Worksheet.Cells[1, 8] = "저가"; Worksheet.Cells[1, 9] = "대비"; Worksheet.Cells[1, 10] = "고가"; Worksheet.Cells[1, 11] = "대비"; Worksheet.Cells[1, 12] = "링크"; Workbook.SaveAs(m_strFileName, Excel.XlFileFormat.xlOpenXMLWorkbook, Missing.Value, Missing.Value, false, false, Excel.XlSaveAsAccessMode.xlNoChange, Excel.XlSaveConflictResolution.xlUserResolution, true, Missing.Value, Missing.Value, Missing.Value); Workbook.Close(); } public void AddRow(string strNewsTime, string strResTime, string strRef, string strTitle, float fReqTime, int iPriceS, int iPriceLow, float fPriceLowP, int iPriceHigh, float fPriceHighP, string strLink) { if(m_bAvailable == false) return; if(File.Exists(m_strFileName) == false) Create(); Excel._Workbook Workbook = m_App.Workbooks.Open(m_strFileName); Excel._Worksheet Worksheet = Workbook.ActiveSheet; int iRow = Worksheet.Cells.SpecialCells(Excel.XlCellType.xlCellTypeLastCell, Type.Missing).Row+1; Worksheet.Cells[iRow, 1] = m_strToday; Worksheet.Cells[iRow, 2] = strNewsTime; Worksheet.Cells[iRow, 3] = strResTime; Worksheet.Cells[iRow, 4] = strRef; Worksheet.Cells[iRow, 5] = strTitle; Worksheet.Cells[iRow, 6] = fReqTime; Worksheet.Cells[iRow, 7] = iPriceS; Worksheet.Cells[iRow, 8] = iPriceLow; Worksheet.Cells[iRow, 9] = fPriceLowP; Worksheet.Cells[iRow, 10] = iPriceHigh; Worksheet.Cells[iRow, 11] = fPriceHighP; Worksheet.Cells[iRow, 12] = strLink; Workbook.Save(); Workbook.Close(); } } }