#include <stdio.h>
#include <sal/main.h>
#include <cppuhelper/bootstrap.hxx>
#include <com/sun/star/frame/Desktop.hpp>
#include <com/sun/star/frame/XComponentLoader.hpp>
#include <com/sun/star/lang/XMultiComponentFactory.hpp>
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#include <com/sun/star/frame/XStorable.hpp>
#include <com/sun/star/lang/XComponent.hpp>
#include <com/sun/star/sheet/XSpreadsheetDocument.hpp>
#include <com/sun/star/container/XIndexAccess.hpp>
#include <com/sun/star/table/XCellRange.hpp>
#include <com/sun/star/beans/XPropertySet.hpp>
#include <com/sun/star/table/TableBorder2.hpp>
#include <com/sun/star/util/XMergeable.hpp>
#include <com/sun/star/table/XColumnRowRange.hpp>



using namespace com::sun::star::util;
using namespace com::sun::star::table;
using namespace com::sun::star::awt;
using namespace com::sun::star::table;
using namespace com::sun::star::container;
using namespace com::sun::star::sheet;
using namespace com::sun::star::beans;
using namespace com::sun::star::uno;
using namespace com::sun::star::lang;
using namespace com::sun::star::frame;
using ::rtl::OUString;
using ::rtl::OUStringToOString;

SAL_IMPLEMENT_MAIN_WITH_ARGS(argc, argv)
{
    try
    {
        //  получаем контекст компонентов офиса
        Reference< XComponentContext > xContext(::cppu::bootstrap());
        if (!xContext.is())
        {
            fprintf(stderr, "no component context!\n");
            return 1;
        }

        // получаем сервис-менеджер
        Reference< XMultiComponentFactory > xServiceManager(
            xContext->getServiceManager());
        if (!xServiceManager.is())
        {
            fprintf(stderr, "no service manager!\n");
            return 1;
        }

        // получаем экземпляр сервиса UNO Desktop
        // получаем интерфейс XComponentLoader
        Reference<XComponentLoader> xLoader(xContext->getServiceManager()->createInstanceWithContext(
            "com.sun.star.frame.Desktop", xContext), UNO_QUERY);


        // создаем новый документ
        Sequence<PropertyValue> props(2);
        PropertyValue prop[2];
        prop[0].Name = "FliterName";
        prop[0].Value <<= OUString("calc8");
        prop[1].Name = "Overwrite";
        prop[1].Value <<= Any(true);
        props[0] = prop[0];
        props[1] = prop[1];
        Reference<XInterface> xComponent = xLoader->loadComponentFromURL(
            "file:///C:/test/document.ods", "_blank", 0, props);

        //Получаем объект документа
        Reference<XSpreadsheetDocument> xDoc(xComponent, UNO_QUERY_THROW);
        //Получаем объект листов
        Reference<XSpreadsheets> xSheets = xDoc->getSheets();
        //Получаем интерфейс XIndexAccess для доступа к элементам по индексу
        Reference<XIndexAccess> xSheetIA(xSheets, UNO_QUERY_THROW);
        //Получаем объект листа с индеком 0 ссылающийся на интерфейс XCellRange
        Reference<XCellRange> xSheet(xSheetIA->getByIndex(0), UNO_QUERY_THROW);
        //Получаем XColumnRowRange для доступа к строкам и столбцам
        Reference<XColumnRowRange> xCRRange(xSheet, UNO_QUERY_THROW);
        //Получаем объект строк
        Reference<XTableRows>xRows(xCRRange->getRows(), UNO_QUERY_THROW);
        //Вставляем две строки на 0 индекс
        xRows->insertByIndex(0, 2);


        // получаем интерфейс XStorable для текущего документа
        Reference< XStorable > xStorable(xComponent, UNO_QUERY);
        if (!xStorable.is())
        {
            fprintf(stderr, "getting XStorable interface failed!\n");
            return 1;
        }

        // задаем URL для сохранения документа
        OUString saveUrl("file:///C:/test/document.ods");

        // сохраняем документ
        xStorable->storeAsURL(saveUrl, props);

        // закрываем документ

       //xDoc->dispose();
    }
    catch (::cppu::BootstrapException& e)
    {
        fprintf(stderr, "caught BootstrapException: %s\n",
            OUStringToOString(e.getMessage(), RTL_TEXTENCODING_ASCII_US).getStr());
        return 1;
    }
    catch (Exception& e)
    {
        fprintf(stderr, "caught UNO exception: %s\n",
            OUStringToOString(e.Message, RTL_TEXTENCODING_ASCII_US).getStr());
        return 1;
    }

    return 0;
}