Files
NewsCrawler/ExcelHandler.cs
2017-01-18 11:07:30 +09:00

120 lines
3.3 KiB
C#

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 = true;
string m_strFileName = "";
string m_strToday = DateTime.Now.ToString("yyyy-MM-dd");
public ExcelHandler(string strFileName)
{
m_strFileName = strFileName;
}
public bool IsAvailable()
{
return m_bAvailable;
}
private void Create()
{
try
{
Excel.Application App = new Excel.Application();
if(App == null)
{
Util.Log(Util.LOG_TYPE.ERROR, "엑셀이 설치되지 않음");
m_bAvailable = false;
return;
}
Excel._Workbook Workbook = 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();
}
catch(Exception ex)
{
Console.WriteLine(ex.Message + Environment.NewLine + ex.StackTrace);
}
}
public bool AddRow(string strNewsTime, string strResTime, string strRef, string strTitle, float fReqTime, int iPriceS, int iPriceLow, float fPriceLowP, int iPriceHigh, float fPriceHighP, string strLink)
{
lock(this)
{
if(m_bAvailable == false)
return false;
if(File.Exists(m_strFileName) == false)
Create();
try
{
Excel.Application App = new Excel.Application();
if(App == null)
{
Util.Log(Util.LOG_TYPE.ERROR, "엑셀이 설치되지 않음");
m_bAvailable = false;
return false;
}
App.DisplayAlerts = false;
Excel._Workbook Workbook = 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();
}
catch(Exception ex)
{
Console.WriteLine(ex.Message + Environment.NewLine + ex.StackTrace);
return false;
}
}
return true;
}
}
}