// Excel1Dlg.cpp : implementation file
//

#include "stdafx.h"
#include "Excel1.h"
#include "Excel1Dlg.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#endif


// CExcel1Dlg dialog


CExcel1Dlg::CExcel1Dlg(CWnd* pParent /*=NULL*/)
	: CDialog(CExcel1Dlg::IDD, pParent)
{
	m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
	//::CoInitializeEx(NULL, 0); // Inicjowanie biblioteki COM
}

void CExcel1Dlg::DoDataExchange(CDataExchange* pDX)
{
    CDialog::DoDataExchange(pDX);
    DDX_Control(pDX, IDC_TREE1, Tree1);
}

BEGIN_MESSAGE_MAP(CExcel1Dlg, CDialog)
	ON_WM_PAINT()
	ON_WM_QUERYDRAGICON()
	//}}AFX_MSG_MAP
    ON_BN_CLICKED(IDC_BUTTON1, &CExcel1Dlg::OnBnClickedButton1)
    ON_BN_CLICKED(IDC_BUTTON2, &CExcel1Dlg::OnBnClickedButton2)
    ON_BN_CLICKED(IDC_BUTTON3, &CExcel1Dlg::OnBnClickedButton3)
    ON_BN_CLICKED(IDC_BUTTON4, &CExcel1Dlg::OnBnClickedButton4)
    ON_BN_CLICKED(IDC_BUTTON5, &CExcel1Dlg::OnBnClickedButton5)
    ON_BN_CLICKED(IDC_BUTTON6, &CExcel1Dlg::OnBnClickedButton6)
END_MESSAGE_MAP()


// CExcel1Dlg message handlers

BOOL CExcel1Dlg::OnInitDialog()
{
	CDialog::OnInitDialog();

	// Set the icon for this dialog.  The framework does this automatically
	//  when the application's main window is not a dialog
	SetIcon(m_hIcon, TRUE);			// Set big icon
	SetIcon(m_hIcon, FALSE);		// Set small icon

	// TODO: Add extra initialization here

	return TRUE;  // return TRUE  unless you set the focus to a control
}

LPDISPATCH CExcel1Dlg::GetIDispatch(CString AppName)
{
    CLSID clsid;
    CLSIDFromProgID(AppName, &clsid);
    IDispatch *pDisp;
    IUnknown *pUnk;
    
    HRESULT hr = GetActiveObject(clsid, NULL, (IUnknown**)&pUnk);
    ASSERT(!FAILED(hr));
        
    hr = pUnk->QueryInterface(IID_IDispatch, (void **)&pDisp);
    ASSERT(!FAILED(hr));

    // Zwolnienie niepotrzebnego już interfejsu IUnknown
    pUnk->Release();
    return pDisp;
}

// If you add a minimize button to your dialog, you will need the code below
//  to draw the icon.  For MFC applications using the document/view model,
//  this is automatically done for you by the framework.

void CExcel1Dlg::OnPaint()
{
	if (IsIconic())
	{
		CPaintDC dc(this); // device context for painting

		SendMessage(WM_ICONERASEBKGND, reinterpret_cast<WPARAM>(dc.GetSafeHdc()), 0);

		// Center icon in client rectangle
		int cxIcon = GetSystemMetrics(SM_CXICON);
		int cyIcon = GetSystemMetrics(SM_CYICON);
		CRect rect;
		GetClientRect(&rect);
		int x = (rect.Width() - cxIcon + 1) / 2;
		int y = (rect.Height() - cyIcon + 1) / 2;

		// Draw the icon
		dc.DrawIcon(x, y, m_hIcon);
	}
	else
	{
		CDialog::OnPaint();
	}
}

// The system calls this function to obtain the cursor to display while the user drags
//  the minimized window.
HCURSOR CExcel1Dlg::OnQueryDragIcon()
{
	return static_cast<HCURSOR>(m_hIcon);
}


void CExcel1Dlg::OnBnClickedButton1()
{
    CWorksheet oSheet;
	CRange oRange;
    LPDISPATCH pDisp;
    
    pDisp = GetIDispatch(L"Excel.Application");
    oExcel.AttachDispatch(pDisp);    
    
    oRange = oExcel.get_ActiveCell(); 
    oSheet = oExcel.get_ActiveSheet();
    oBook = oExcel.get_ActiveWorkbook();
    
    CString adres = oRange.get_Address(COleVariant((short)TRUE), 
        COleVariant((short)TRUE), 1, COleVariant((short)FALSE), 
        COleVariant((short)FALSE));
	
	VARIANT val = oRange.get_Value2();
	
	MessageBox(L"Nazwa otwartego skoroszytu: " + oBook.get_Name() + L"\nNazwa otwartego arkusza: " +
	    oSheet.get_Name() + L"\nAdres aktywnej komórki: " + adres + L"\nWartość aktywnej komórki: " + 
	    (CString)val); 
	
	oExcel.ReleaseDispatch(); // Odłączanie od Excela
}

void CExcel1Dlg::OnBnClickedButton2()
{
    COleException e;
    CWorkbooks oBooks;
	CWorksheets oSheets;
	CWorksheet oSheet;
    COleVariant covOptional(DISP_E_PARAMNOTFOUND,VT_ERROR); // Parametr opcjonalny

    if(!oExcel.CreateDispatch(L"Excel.Application", &e))
    {
        e.ReportError();
        return;
    }
    else
    {
        oExcel.put_Visible(TRUE);
        oExcel.put_UserControl(TRUE);
        
	    // Dodanie nowego skoroszytu i pobranie pierwszego arkusza
	    oBooks = oExcel.get_Workbooks();
	    oBook = oBooks.Add(covOptional);
	    oSheets = oBook.get_Worksheets();
	    oSheet = oSheets.get_Item(COleVariant((short)1));  
	    oExcel.ReleaseDispatch();
    }
}

void CExcel1Dlg::OnBnClickedButton3()
{
    LPDISPATCH pDisp = GetIDispatch(L"Excel.Application");
    oExcel.AttachDispatch(pDisp);
    oExcel.Quit();
    oExcel.ReleaseDispatch();
}

void CExcel1Dlg::OnBnClickedButton4()
{
    LPDISPATCH pDisp = GetIDispatch(L"Excel.Application");  
    oExcel.AttachDispatch(pDisp);      
    CWorkbooks workbooks = oExcel.get_Workbooks();
    CWorksheets worksheets;
    CWorkbook workbook;
    CWorksheet worksheet;
        
    Tree1.DeleteAllItems();
        
    for(int i = 1; i <= workbooks.get_Count(); i++)
    {
        workbook = workbooks.get_Item(COleVariant((short)i));
        worksheets = workbook.get_Worksheets();
        HTREEITEM hWorkbook = Tree1.InsertItem(workbook.get_Name(), 
            NULL, NULL);
                
        for(int j = 1; j <= worksheets.get_Count(); j++)
        {
            worksheet = worksheets.get_Item(COleVariant((short)j));
            HTREEITEM hSheet = Tree1.InsertItem(worksheet.get_Name(),
                hWorkbook, NULL);
        }
    }    
    
    oExcel.ReleaseDispatch(); 
}

void CExcel1Dlg::OnBnClickedButton5()
{
    LPDISPATCH pDisp = GetIDispatch(L"Excel.Application");  
    oExcel.AttachDispatch(pDisp);
        
    CString nazwaPliku;
        
    nazwaPliku = oExcel.GetSaveAsFilename(COleVariant(), 
        COleVariant(L"Arkusze Excel (*.xls), *xls,Wszystkie pliki (*.*), *.*"),
        COleVariant(), COleVariant(), COleVariant());
    oExcel.Save(COleVariant(nazwaPliku));
        
    MessageBox(L"Dane zapisane w pliku " + nazwaPliku);
}

void CExcel1Dlg::OnBnClickedButton6()
{
    LPDISPATCH pDisp = GetIDispatch(L"Excel.Application");  
    oExcel.AttachDispatch(pDisp);
        
    CFileDialog fileDialog(FALSE, 0, 0, 2, 
        L"Arkusze Excel (*.xls)|*.xls|Wszystkie pliki (*.xls)|*.xls||");
            
    if(fileDialog.DoModal() != IDCANCEL)
    {
        CString nazwaPliku = fileDialog.GetPathName();
        oExcel.Save(COleVariant(nazwaPliku));
        MessageBox(L"Dane zapisane w pliku " + nazwaPliku);
    }
    else
        MessageBox(L"Anulowano zapisanie do pliku");
}
