//---------------------------------------------------------------------------
void OfficeSaveAsDoc(AnsiString Office, Variant Document, AnsiString FileName)
{
 //сохранить документ как
  try
    {
     if (Office=="OO")
      {
        Variant SaveParam;
        int Bounds[2] = {0,0};
        Variant ServiceManager = Variant::CreateObject("com.sun.star.ServiceManager");
        Variant MyStruct = ServiceManager.OleFunction("Bridge_GetStruct", "com.sun.star.beans.PropertyValue");
        MyStruct.OlePropertySet("name","FilterName");
        MyStruct.OlePropertySet("value","MS Word 97");
        SaveParam = VarArrayCreate(Bounds, 1, varVariant);
        SaveParam.PutElement(MyStruct, 0);
        Document.OleFunction ("storeAsURL", convertToURL(FileName), SaveParam);
        ServiceManager = Unassigned;
      }
     if (Office=="MSO")
      {
        Document.OleProcedure("SaveAs", FileName);
      }
    }
  catch (Exception &E)
    {
     ShowMessage("Ошибка при сохранении документа как " + E.Message);
    }
}
Example #2
0
void __fastcall TForm1::actSortClassificationsExecute(TObject *Sender)
{
	if(!MakeBackup()) {
		Log->Lines->Add("Ошибка: Не удалось создать резервную копию файла");
		return;
	}

	Variant app = Variant::CreateObject("Excel.Application");
	app.OlePropertySet("Visible", true);
	Variant excel = app.OlePropertyGet("Workbooks").OleFunction("Open", WideString(m_strFileName.c_str()));
	Variant vSheets = excel.OlePropertyGet("Worksheets");

	Variant vSheet = vSheets.OlePropertyGet("Item",m_nPageClassification);
	UnicodeString strPageName = vSheet.OlePropertyGet("Name");
	if (strPageName.UpperCase() != UnicodeString("классификации").UpperCase()) {
	   app.OleProcedure("Quit");
	   Log->Lines->Add("Ошибка: Не верное имя страницы");
	   MessageBox (Handle, UnicodeString(L"Не верное имя страницы").c_str(), L"prompt", MB_OK);
	   return;
	};
	std::vector<exlClass> classes;
	ReadClassifications(vSheet, classes);
	WriteClassifications(vSheet, classes);


	Log->Lines->Add("Сохраняю файл...");
	try {
		app.OlePropertySet("DisplayAlerts",false);
		excel.OleProcedure("SaveAs", WideString(m_strFileName.c_str()));
		Log->Lines->Add("Классификации отсортированы!");
	} catch (...) {
		Log->Lines->Add("Ошибка: Пожалуйста закройте все открытые копии файла и повторите операцию");
	}
	app.OleProcedure("Quit");
}
//---------------------------------------------------------------------------
Variant OfficeOpenDoc(AnsiString Office, Variant *app, AnsiString FileName)
{
// открыть документ
  try
    {
     Variant vApp, Document;
     if (Office=="OO")
      {
       Variant Desktop;
       Variant OpenParams;
       int Bounds[2] = {0,0};

       vApp = Variant::CreateObject("com.sun.star.ServiceManager");
       Desktop = vApp.OleFunction("createInstance", "com.sun.star.frame.Desktop");
       OpenParams = VarArrayCreate(Bounds, 1, varVariant);
       Variant MyStruct = vApp.OleFunction("Bridge_GetStruct","com.sun.star.beans.PropertyValue");
       MyStruct.OlePropertySet("name","Hidden");
       MyStruct.OlePropertySet("value",true);
       OpenParams.PutElement(MyStruct, 0);
       Document = Desktop.OleFunction("LoadComponentFromURL", convertToURL(FileName), "_blank", 0, OpenParams );
      }
     if (Office=="MSO")
      {
       Variant word_docs;
       vApp = Variant::CreateObject("word.application");
       word_docs = vApp.OlePropertyGet("Documents");
       Document = word_docs.OleFunction("Open" ,FileName.c_str());
      }
	 *app = vApp;
	 return Document;
    }
  catch (Exception &E)
    {
     ShowMessage("Ошибка при открытии документа " + E.Message);
     return 0;
    }
}
//---------------------------------------------------------------------------
void OfficeVisible(AnsiString Office, Variant app, Variant Document, bool Visible)
{
//показать документ
  try
    {
     if (Office=="OO")
      {
       Variant Frame, CurrentController, ContainerWindow;
       CurrentController = Document.OleFunction("getCurrentController");
       Frame = CurrentController.OleFunction("getFrame");
       ContainerWindow = Frame.OleFunction("getContainerWindow");
       ContainerWindow.OleFunction("setVisible",Visible);
      }
     if (Office=="MSO")
	  {
       app.OlePropertySet("Visible", Visible);
      }
    }
  catch (Exception &E)
    {
     ShowMessage("Ошибка при попытке показать документ " + E.Message);
    }
}
//---------------------------------------------------------------------------
void OfficeFindReplace(AnsiString Office, Variant app, Variant Document, AnsiString sFind, AnsiString sReplace)
{
//найти и заменить с параметрами
  try
    {
     if (Office=="OO")
      {
      /*
       //найти и заменить без параметров
       Variant FindParam = Document.OleFunction("createSearchDescriptor");
       FindParam.OlePropertySet("SearchString", sFind);
       FindParam.OlePropertySet("ReplaceString", sReplace);
       Document.OleFunction("ReplaceAll", FindParam);
       */
       Variant ServiceManager;
       ServiceManager = Variant::CreateObject("com.sun.star.ServiceManager");

       Variant MyStruct3 = ServiceManager.OleFunction("Bridge_GetStruct", "com.sun.star.beans.PropertyValue");
       MyStruct3.OlePropertySet("name",        "SearchItem.StyleFamily");
       MyStruct3.OlePropertySet("value",        2);
       Variant MyStruct4 = ServiceManager.OleFunction("Bridge_GetStruct", "com.sun.star.beans.PropertyValue");
       MyStruct4.OlePropertySet("name",        "SearchItem.CellType");
       MyStruct4.OlePropertySet("value",        0);
       Variant MyStruct5 = ServiceManager.OleFunction("Bridge_GetStruct", "com.sun.star.beans.PropertyValue");
       MyStruct5.OlePropertySet("name",        "SearchItem.RowDirection");
       MyStruct5.OlePropertySet("value",        true);
       Variant MyStruct6 = ServiceManager.OleFunction("Bridge_GetStruct", "com.sun.star.beans.PropertyValue");
       MyStruct6.OlePropertySet("name",        "SearchItem.AllTables");
       MyStruct6.OlePropertySet("value",        false);
       Variant MyStruct7 = ServiceManager.OleFunction("Bridge_GetStruct", "com.sun.star.beans.PropertyValue");
       MyStruct7.OlePropertySet("name",        "SearchItem.Backward");
       MyStruct7.OlePropertySet("value",        false);
       Variant MyStruct8 = ServiceManager.OleFunction("Bridge_GetStruct", "com.sun.star.beans.PropertyValue");
       MyStruct8.OlePropertySet("name",        "SearchItem.Pattern");
       MyStruct8.OlePropertySet("value",        false);
       Variant MyStruct9 = ServiceManager.OleFunction("Bridge_GetStruct", "com.sun.star.beans.PropertyValue");
       MyStruct9.OlePropertySet("name",        "SearchItem.Content");
       MyStruct9.OlePropertySet("value",        false);
       Variant MyStruct10 = ServiceManager.OleFunction("Bridge_GetStruct", "com.sun.star.beans.PropertyValue");
       MyStruct10.OlePropertySet("name",        "SearchItem.AsianOptions");
       MyStruct10.OlePropertySet("value",        false);
       Variant MyStruct11 = ServiceManager.OleFunction("Bridge_GetStruct", "com.sun.star.beans.PropertyValue");
       MyStruct11.OlePropertySet("name",        "SearchItem.AlgorithmType");
       MyStruct11.OlePropertySet("value",        0);

       Variant MyStruct2 = ServiceManager.OleFunction("Bridge_GetStruct", "com.sun.star.beans.PropertyValue");
       MyStruct2.OlePropertySet("name",       "SearchItem.SearchFlags");
       MyStruct2.OlePropertySet("value",      65552); // флаг 65536 - часть или все слово
       Variant MyStruct = ServiceManager.OleFunction("Bridge_GetStruct", "com.sun.star.beans.PropertyValue");
       MyStruct.OlePropertySet("name",        "SearchItem.SearchString");
       MyStruct.OlePropertySet("value",       sFind);
       Variant MyStruct1 = ServiceManager.OleFunction("Bridge_GetStruct", "com.sun.star.beans.PropertyValue");
       MyStruct1.OlePropertySet("name",       "SearchItem.ReplaceString");
       MyStruct1.OlePropertySet("value",      sReplace);

       Variant MyStruct12 = ServiceManager.OleFunction("Bridge_GetStruct", "com.sun.star.beans.PropertyValue");
       MyStruct12.OlePropertySet("name",        "SearchItem.Locale");
       MyStruct12.OlePropertySet("value",        255);
       Variant MyStruct13 = ServiceManager.OleFunction("Bridge_GetStruct", "com.sun.star.beans.PropertyValue");
       MyStruct13.OlePropertySet("name",        "SearchItem.ChangedChars");
       MyStruct13.OlePropertySet("value",        2);
       Variant MyStruct14 = ServiceManager.OleFunction("Bridge_GetStruct", "com.sun.star.beans.PropertyValue");
       MyStruct14.OlePropertySet("name",        "SearchItem.DeletedChars");
       MyStruct14.OlePropertySet("value",        2);
       Variant MyStruct15 = ServiceManager.OleFunction("Bridge_GetStruct", "com.sun.star.beans.PropertyValue");
       MyStruct15.OlePropertySet("name",        "SearchItem.InsertedChars");
       MyStruct15.OlePropertySet("value",        2);
       Variant MyStruct16 = ServiceManager.OleFunction("Bridge_GetStruct", "com.sun.star.beans.PropertyValue");
       MyStruct16.OlePropertySet("name",        "SearchItem.TransliterateFlags");
       MyStruct16.OlePropertySet("value",        1024);
       Variant MyStruct17 = ServiceManager.OleFunction("Bridge_GetStruct", "com.sun.star.beans.PropertyValue");
       MyStruct17.OlePropertySet("name",        "SearchItem.Command");
       MyStruct17.OlePropertySet("value",        3);
       Variant MyStruct18 = ServiceManager.OleFunction("Bridge_GetStruct", "com.sun.star.beans.PropertyValue");
       MyStruct18.OlePropertySet("name",        "Quiet");
       MyStruct18.OlePropertySet("value",        true);

       int Bounds[2] = {0,18}; // на 18 шт
       Variant SearchParam = VarArrayCreate(Bounds, 1, varVariant);

       SearchParam.PutElement(MyStruct3, 3);
       SearchParam.PutElement(MyStruct4, 4);
       SearchParam.PutElement(MyStruct5, 5);
       SearchParam.PutElement(MyStruct6, 6);
       SearchParam.PutElement(MyStruct7, 7);
       SearchParam.PutElement(MyStruct8, 8);
       SearchParam.PutElement(MyStruct9, 9);
       SearchParam.PutElement(MyStruct10, 10);
       SearchParam.PutElement(MyStruct11, 11);

       SearchParam.PutElement(MyStruct, 0);
       SearchParam.PutElement(MyStruct1, 1);
       SearchParam.PutElement(MyStruct2, 2);

       SearchParam.PutElement(MyStruct12, 12);
       SearchParam.PutElement(MyStruct13, 13);
       SearchParam.PutElement(MyStruct14, 14);
       SearchParam.PutElement(MyStruct15, 15);
       SearchParam.PutElement(MyStruct16, 16);
       SearchParam.PutElement(MyStruct17, 17);
       SearchParam.PutElement(MyStruct18, 18);


       Variant Dispatcher, Frame, CurrentController;
	   CurrentController = Document.OleFunction("getCurrentController");
       Frame = CurrentController.OleFunction("getFrame");
	   Dispatcher= ServiceManager.OleFunction("createInstance", "com.sun.star.frame.DispatchHelper");
       Dispatcher.OleFunction("executeDispatch", Frame, ".uno:ExecuteSearch", "", 0, SearchParam);
      }
	 if (Office=="MSO")
      {
		Variant this_selection, this_find;
		this_selection = app.OlePropertyGet("Selection") ;
	   //	this_selection.OleFunction("GoTo", 4294967295, 0, 0, Document);
		this_find = this_selection.OlePropertyGet("Find") ;
        //---Запуск обработки
		this_find.OleProcedure ("Execute",
		/* FindText          */      sFind.c_str(),
		/* MatchCase         */      false,
		/* MatchWholeWord    */      false, //  false - часть или все слово
        /* MatchWildcards    */      false,
        /* MatchSoundsLike   */      false,
        /* MatchAllWordForms */      false,
        /* Forward           */      true,
        /* Wrap              */      1,
        /* Format            */      false,
		/* ReplaceWith       */      sReplace.c_str(),
        /* Replace           */      2
		);
      }
    }
  catch (Exception &E)
    {
	 ShowMessage("Ошибка при поиске и замене " + E.Message);
    }
}
//---------------------------------------------------------------------------
void OfficePrintParam(AnsiString Office, Variant app, Variant Document, int vCopies, AnsiString vRangeText, AnsiString vPrinter)
{
//Печать страницы vRangeText  в vCopies экземплярах и выбор принтера vPrinter
//для ОО после выбора принтера документ надо сохранять заново
  try
    {
     if (Office=="OO")
      {
       Variant ServiceManager;
       ServiceManager = Variant::CreateObject("com.sun.star.ServiceManager");
       Variant MyStruct = ServiceManager.OleFunction("Bridge_GetStruct", "com.sun.star.beans.PropertyValue");
       MyStruct.OlePropertySet("name",        "Copies");
       MyStruct.OlePropertySet("value",        vCopies);
       Variant MyStruct_1 = ServiceManager.OleFunction("Bridge_GetStruct", "com.sun.star.beans.PropertyValue");
       MyStruct_1.OlePropertySet("name",        "RangeText");
       MyStruct_1.OlePropertySet("value",        vRangeText); //Тут можно указать диапазон "1,5-7"
       Variant MyStruct_2 = ServiceManager.OleFunction("Bridge_GetStruct", "com.sun.star.beans.PropertyValue");
       MyStruct_2.OlePropertySet("name",        "Collate");
       MyStruct_2.OlePropertySet("value",        false);

       int Bounds[2] = {0,2};
       Variant PrintParam = VarArrayCreate(Bounds, 1, varVariant);
       PrintParam.PutElement(MyStruct, 0);
       PrintParam.PutElement(MyStruct_1, 1);
       PrintParam.PutElement(MyStruct_2, 2);

       //выбор принтера
        Variant PrintDescStruct = ServiceManager.OleFunction("Bridge_GetStruct", "com.sun.star.beans.PropertyValue");
        PrintDescStruct.OlePropertySet("Name", "Name");
        PrintDescStruct.OlePropertySet("Value", vPrinter);
        int PrintDescBounds[2] = {0,0};
        Variant PrintDesc = VarArrayCreate(PrintDescBounds, 1, varVariant);
        PrintDesc.PutElement(PrintDescStruct, 0);
        Document.OleFunction("setPrinter", PrintDesc);

       Variant Dispatcher, Frame, CurrentController;
       CurrentController = Document.OleFunction("getCurrentController");
       Frame = CurrentController.OleFunction("getFrame");

       Dispatcher= ServiceManager.OleFunction("createInstance", "com.sun.star.frame.DispatchHelper");
       //с пустыми или не верными параметрами PrintParam выскакивает окно печати!
       Dispatcher.OleFunction("executeDispatch", Frame, ".uno:Print", "", 0, PrintParam);

      //нужно это или нет, не знаю
       PrintParam = Unassigned;
       PrintDesc  = Unassigned;
      }
     if (Office=="MSO")
      {
	   app.OlePropertySet("ActivePrinter", vPrinter);
       OleVariant
           tr = true,
           fl=false,
           copies= vCopies,
		   _Range= 4, //wdPrintRangeOfPages
		   _Item=  0, //wdPrintDocumentContent
		   _PageType= 0, //wdPrintAllPages
           _FileName=(AnsiString)"",
           _page=(AnsiString)vRangeText;
	   app.OleFunction("PrintOut", fl, fl, _Range, _FileName, "",
									"", _Item, copies, _page, _PageType, fl,
									tr, "", "");
      }
    }
  catch (Exception &E)
    {
     ShowMessage("Ошибка при печати с параметрами " + E.Message);
    }
}
Example #7
0
void __fastcall TForm1::actRedesignClassificationsExecute(TObject *Sender)
{
	lblStatus->Caption = "";
	if(!MakeBackup()) {
		Log->Lines->Add("Не удалось создать резервную копию файла");
		lblStatus->Caption = "Ошибка: Не удалось создать резервную копию файла";
		return;
	}
	m_strRecomendations = "";

	lblStatus->Caption = "Открываю файл на чтение...";
	Variant app = Variant::CreateObject("Excel.Application");
    app.OlePropertySet("Visible", true);
	Variant excel = app.OlePropertyGet("Workbooks").OleFunction("Open", WideString(m_strFileName.c_str()));
	Variant vSheets = excel.OlePropertyGet("Worksheets");
	Variant vSheet = vSheets.OlePropertyGet("Item",m_nPageClassification);
	UnicodeString strPageName = vSheet.OlePropertyGet("Name");
	if (strPageName.UpperCase() != UnicodeString("классификации").UpperCase()) {
		app.OleProcedure("Quit");
		MessageBox (Handle, UnicodeString(L"Не верное имя страницы").c_str(), L"prompt", MB_OK);
		lblStatus->Caption = "Ошибка: Не верное имя страницы";
		return;
	};

	std::vector<exlClass> classes;
	ReadClassifications(vSheet, classes);

	std::vector<exlMonth> months;
	for (unsigned int i = 0; i < m_vMonth.size(); i++) {
		int nMonthPage = m_vMonth[i].Number;
		Variant vSheetMonth = vSheets.OlePropertyGet("Item",nMonthPage);
		ReadMonth(vSheetMonth, months);
	}
//	Log->Lines->Add("Обновляю линки." + IntToStr((int)months.size()));

	int nAll = classes.size() * months.size();
	Log->Lines->Add("Всего записей в месяцах: " + IntToStr((int)months.size()));
	std::vector<exlClass> newclasses;
	int nRemovedClasses = 0;
	ProgressBar1->Max = nAll;
	ProgressBar1->Min = 0;
	ProgressBar1->Position = 0;

	lblStatus->Caption = "Поиск наименований которые отсутвуют в месяцах...";
	Log->Lines->Add("Произвожу поиск наименований которые отсутвуют в месяцах...");
	for (unsigned int iC = 0; iC < classes.size(); iC++) {
		exlClass cl = classes[iC];
		cl.Monthes = "";
		UnicodeString name = classes[iC].Name.UpperCase();
		int nCount = 0;
		for (unsigned int iM = 0; iM < months.size(); iM++) {
			ProgressBar1->Position++;
			Application->ProcessMessages();
			UnicodeString name2 = months[iM].Name.UpperCase();
			if (name == name2) {
			   nCount++;
			   if (cl.Monthes.Pos(months[iM].Month) < 1) {
				  cl.Monthes += months[iM].Month + ";";
			   }
			}
		}
		if (nCount > 0) {
			newclasses.push_back(cl);
		} else {
			nRemovedClasses++;
			Log->Lines->Add("\tНаименование '" + cl.Name + "' - нигде не встречается и будет удалено из классификаций");
		}
	}
	Log->Lines->Add(" ** ");

	nAll = newclasses.size() * months.size();
	ProgressBar1->Max = nAll;
	ProgressBar1->Min = 0;
	ProgressBar1->Position = 0;
	int nAddClasses = 0;
	lblStatus->Caption = "Поиск наименований которые отсутвуют в списке классификаций...";
	Log->Lines->Add("Произвожу поиск наименований которые отсутвуют в списке классификаций...");
	for (unsigned int iM = 0; iM < months.size(); iM++) {
		UnicodeString name = months[iM].Name.UpperCase();
		int nCount = 0;
		for (unsigned int iC = 0; iC < newclasses.size(); iC++) {
			ProgressBar1->Position++;
			Application->ProcessMessages();
			UnicodeString name2 = newclasses[iC].Name.UpperCase();
			if (name == name2) {
			   nCount++;
			}
		}
		if (nCount == 0) {
			Log->Lines->Add("\tНаименование '" + months[iM].Name + "' - будет добавлено в классификации");
			exlClass cl;
			cl.Name = months[iM].Name;
			cl.Class = m_sUnknownClass;
			cl.Monthes += months[iM].Month + ";";
			newclasses.push_back(cl);
			nAddClasses++;

			nAll = newclasses.size() * months.size();
			ProgressBar1->Max = nAll;
		}
	}
	Log->Lines->Add("Будет удалено классификаций: " + IntToStr(nRemovedClasses));
    Log->Lines->Add("Будет добавлено классификаций: " + IntToStr(nAddClasses));
	Log->Lines->Add("Всего классификаций: " + IntToStr((int)(newclasses.size())));


	WriteClassifications(vSheet, newclasses);

	lblStatus->Caption = "Сохраняю файл...";
	Log->Lines->Add("Сохраняю файл...");
	try {
		app.OlePropertySet("DisplayAlerts",false);
		excel.OleProcedure("SaveAs", WideString(m_strFileName.c_str()));
		Log->Lines->Add("Данные сохранены!");
	} catch (...) {
		lblStatus->Caption = "Ошибка: Пожалуйста закройте все открытые копии файла и повторите операцию";
		Log->Lines->Add("Ошибка: Пожалуйста закройте все открытые копии файла и повторите операцию");
	}
    ProgressBar1->Position = 0;
	app.OleProcedure("Quit");
	lblStatus->Caption = "";
}
Example #8
0
void __fastcall TForm1::actCalcClassificationExecute(TObject *Sender)
{
	if(!MakeBackup()) {
		Log->Lines->Add("Не удалось создать резервную копию файла");
		return;
	}

	Variant app = Variant::CreateObject("Excel.Application");
	app.OlePropertySet("Visible", true);
	Variant excel = app.OlePropertyGet("Workbooks").OleFunction("Open", WideString(m_strFileName.c_str()));
	Variant vSheets = excel.OlePropertyGet("Worksheets");
	Variant vSheet = vSheets.OlePropertyGet("Item",m_nPageClassification);
	UnicodeString strPageName = vSheet.OlePropertyGet("Name");
	if (strPageName.UpperCase() != UnicodeString("классификации").UpperCase()) {
	   app.OleProcedure("Quit");
	   MessageBox (Handle, UnicodeString(L"Не верное имя страницы").c_str(), L"prompt", MB_OK);
	   return;
	};

	std::vector<exlClass> classes;
	ReadClassifications(vSheet, classes);

	std::vector<exlMonth> months;
	Variant vSheetMonth;
	double fSumSum = 0;
	for (unsigned int i = 0; i < m_vMonth.size(); i++) {
		if (cmbMonth->Text == m_vMonth[i].Name) {
			int nMonthPage = m_vMonth[i].Number;
			vSheetMonth = vSheets.OlePropertyGet("Item", nMonthPage);
			ReadMonth(vSheetMonth, months);
			ReadMonthSum(vSheetMonth, fSumSum);
		}
	}

	Log->Lines->Add("Произвожу расчет...");
    ProgressBar1->Max = months.size();
	ProgressBar1->Min = 0;
	double nSumHand = 0;

	std::vector<exlSumClass> vSumClasses;
	for (unsigned int i = 0; i < months.size(); i++) {
		ProgressBar1->Position = i;
		int nFound = 0;
		nSumHand += months[i].Price;
		for (unsigned int iC = 0; iC < classes.size(); iC++) {
			if (nFound == 0 && classes[iC].Name.UpperCase() == months[i].Name.UpperCase()) {
				months[i].Class = classes[iC].Class;
				months[i].LinkToClassification = createHyperLinkToClassification(classes, iC);
				nFound++;
			}
		}
		if (nFound == 0) {
			months[i].Class = m_sUnknownClass;
		}

		nFound = 0;
		for (unsigned int iC = 0; iC < vSumClasses.size(); iC++) {
			if (vSumClasses[iC].Name.UpperCase() == months[i].Class.UpperCase()) {
				vSumClasses[iC].Sum += months[i].Price;
				nFound++;
			}
		}
		if (nFound == 0) {
		   exlSumClass sm;
		   sm.Name = months[i].Class;
		   sm.Sum = months[i].Price;
		   vSumClasses.push_back(sm);
		}
	}

	/*for (unsigned int i = 0; i < vSumClasses.size(); i++) {
		Log->Lines->Add(vSumClasses[i].Name + " = " + FloatToStr(vSumClasses[i].Sum));
	}*/

	Log->Lines->Add("Готово.");

	Log->Lines->Add("Сортирую классификации...");
	ProgressBar1->Max = 100;
	ProgressBar1->Min = 0;

	{
		int nPermutation = 1;
		while (nPermutation > 0) {
			nPermutation = 0;
			for (unsigned int iC = 0; iC < vSumClasses.size()-1; iC++) {
				ProgressBar1->Position = (ProgressBar1->Position+1) % ProgressBar1->Max;
				Application->ProcessMessages();
				if (vSumClasses[iC].Name.UpperCase() > vSumClasses[iC+1].Name.UpperCase()) {
					exlSumClass buf = vSumClasses[iC];
					vSumClasses[iC] = vSumClasses[iC+1];
					vSumClasses[iC+1] = buf;
					nPermutation++;
				}
			}
		}
		ProgressBar1->Position = 0;
    }
	Log->Lines->Add("Готово.");

	Log->Lines->Add("Очистка старых данных");
	ProgressBar1->Max = 100;
	ProgressBar1->Min = 0;

	// clear sum classes, 11,12
	{
		bool b = true;
		int nRow = 1;
		while (b) {
			b = false;
			nRow++;
			ProgressBar1->Position = (ProgressBar1->Position+1) % ProgressBar1->Max;
			Application->ProcessMessages();

			vSheetMonth.OlePropertyGet("Cells").OlePropertyGet("Item",nRow,11).OleProcedure("ClearFormats");
			vSheetMonth.OlePropertyGet("Cells").OlePropertyGet("Item",nRow,12).OleProcedure("ClearFormats");

			UnicodeString sValue11 = vSheetMonth.OlePropertyGet("Cells").OlePropertyGet("Item",nRow,11).OlePropertyGet("Value");
			UnicodeString sValue12 = vSheetMonth.OlePropertyGet("Cells").OlePropertyGet("Item",nRow,12).OlePropertyGet("Value");

			clearCell(vSheetMonth, nRow, 11);
			clearCell(vSheetMonth, nRow, 12);

			if (sValue12.Trim().Length() > 0 || sValue11.Trim().Length() > 0) {
				b = true;
			}
		}
		ProgressBar1->Position = 0;
	}

	// clear 14,15,16,17
	{
		bool b = true;
		int nRow = 1;
		while (b) {
			b = false;
			nRow++;
			ProgressBar1->Position = (ProgressBar1->Position+1) % ProgressBar1->Max;
			Application->ProcessMessages();

			vSheetMonth.OlePropertyGet("Cells").OlePropertyGet("Item",nRow,14).OleProcedure("ClearFormats");
			vSheetMonth.OlePropertyGet("Cells").OlePropertyGet("Item",nRow,15).OleProcedure("ClearFormats");
			vSheetMonth.OlePropertyGet("Cells").OlePropertyGet("Item",nRow,16).OleProcedure("ClearFormats");
			vSheetMonth.OlePropertyGet("Cells").OlePropertyGet("Item",nRow,17).OleProcedure("ClearFormats");

			UnicodeString sValue14 = vSheetMonth.OlePropertyGet("Cells").OlePropertyGet("Item",nRow,14).OlePropertyGet("Value");
			UnicodeString sValue15 = vSheetMonth.OlePropertyGet("Cells").OlePropertyGet("Item",nRow,15).OlePropertyGet("Value");
			UnicodeString sValue16 = vSheetMonth.OlePropertyGet("Cells").OlePropertyGet("Item",nRow,16).OlePropertyGet("Value");
			UnicodeString sValue17 = vSheetMonth.OlePropertyGet("Cells").OlePropertyGet("Item",nRow,17).OlePropertyGet("Value");

			clearCell(vSheetMonth, nRow, 14);
			clearCell(vSheetMonth, nRow, 15);
			clearCell(vSheetMonth, nRow, 16);
			clearCell(vSheetMonth, nRow, 17);

			if (
				sValue14.Trim().Length() > 0
				|| sValue15.Trim().Length() > 0
				|| sValue16.Trim().Length() > 0
				|| sValue17.Trim().Length() > 0
			) {
				b = true;
			}
		}
		ProgressBar1->Position = 0;
	}


	Log->Lines->Add("Запись новых данных");
	{
		double nSum = 0;
		int nRow = 2;
		vSheetMonth.OlePropertyGet("Cells").OlePropertyGet("Item",nRow,11).OlePropertySet("Value", WideString("Класс"));
		vSheetMonth.OlePropertyGet("Cells").OlePropertyGet("Item",nRow,12).OlePropertySet("Value", WideString("Сумма"));
		vSheetMonth.OlePropertyGet("Cells").OlePropertyGet("Item",nRow,11).OlePropertyGet("Font").OlePropertySet("Bold", true);
		vSheetMonth.OlePropertyGet("Cells").OlePropertyGet("Item",nRow,12).OlePropertyGet("Font").OlePropertySet("Bold", true);
		vSheetMonth.OlePropertyGet("Columns", WideString("K")).OlePropertySet("ColumnWidth", 20);
		vSheetMonth.OlePropertyGet("Columns", WideString("L")).OlePropertySet("ColumnWidth", 15);
		setBorders(vSheetMonth, nRow, 11);
		setBorders(vSheetMonth, nRow, 12);
		setColor(vSheetMonth, nRow, 11, RGBToInt(240, 230, 140));
		setColor(vSheetMonth, nRow, 12, RGBToInt(240, 230, 140));

		ProgressBar1->Max = vSumClasses.size();
		ProgressBar1->Min = 0;
		for (unsigned int i = 0; i < vSumClasses.size(); i++) {
			nRow++;
			ProgressBar1->Position = i;
			nSum += vSumClasses[i].Sum;
			vSheetMonth.OlePropertyGet("Cells").OlePropertyGet("Item",nRow,11).OlePropertySet("Value", WideString(vSumClasses[i].Name));
			vSheetMonth.OlePropertyGet("Cells").OlePropertyGet("Item",nRow,12).OlePropertySet("Value", WideString(vSumClasses[i].Sum));

			vSheetMonth.OlePropertyGet("Cells").OlePropertyGet("Item",nRow,12).OlePropertySet("NumberFormat", WideString(m_strNumberFormat));

			setBorders(vSheetMonth, nRow, 11);
			setBorders(vSheetMonth, nRow, 12);
		}
		nRow++;
		ProgressBar1->Position = 0;

		vSheetMonth.OlePropertyGet("Cells").OlePropertyGet("Item",nRow,11).OlePropertySet("Value", WideString("Итого:"));
		vSheetMonth.OlePropertyGet("Cells").OlePropertyGet("Item",nRow,12).OlePropertySet("Value", WideString(nSum));
		vSheetMonth.OlePropertyGet("Cells").OlePropertyGet("Item",nRow,12).OlePropertySet("NumberFormat", WideString(m_strNumberFormat));

		nRow++;

		vSheetMonth.OlePropertyGet("Cells").OlePropertyGet("Item",nRow,11).OlePropertySet("Value", WideString("Сумма сумм по дням:"));
		vSheetMonth.OlePropertyGet("Cells").OlePropertyGet("Item",nRow,12).OlePropertySet("Value", WideString(fSumSum));
		vSheetMonth.OlePropertyGet("Cells").OlePropertyGet("Item",nRow,12).OlePropertySet("NumberFormat", WideString(m_strNumberFormat));
	}

	{
		double nSum = 0;
		int nRow = 2;
		vSheetMonth.OlePropertyGet("Cells").OlePropertyGet("Item",nRow,14).OlePropertySet("Value", WideString("Класс"));
		vSheetMonth.OlePropertyGet("Cells").OlePropertyGet("Item",nRow,15).OlePropertySet("Value", WideString("Наименование"));
		vSheetMonth.OlePropertyGet("Cells").OlePropertyGet("Item",nRow,16).OlePropertySet("Value", WideString("Цена"));
		vSheetMonth.OlePropertyGet("Cells").OlePropertyGet("Item",nRow,17).OlePropertySet("Value", WideString("Ссылка"));

		vSheetMonth.OlePropertyGet("Cells").OlePropertyGet("Item",nRow,14).OlePropertyGet("Font").OlePropertySet("Bold", true);
		vSheetMonth.OlePropertyGet("Cells").OlePropertyGet("Item",nRow,15).OlePropertyGet("Font").OlePropertySet("Bold", true);
		vSheetMonth.OlePropertyGet("Cells").OlePropertyGet("Item",nRow,16).OlePropertyGet("Font").OlePropertySet("Bold", true);
		vSheetMonth.OlePropertyGet("Cells").OlePropertyGet("Item",nRow,17).OlePropertyGet("Font").OlePropertySet("Bold", true);

		vSheetMonth.OlePropertyGet("Columns", WideString("N")).OlePropertySet("ColumnWidth", 20);
		vSheetMonth.OlePropertyGet("Columns", WideString("O")).OlePropertySet("ColumnWidth", 50);
		vSheetMonth.OlePropertyGet("Columns", WideString("P")).OlePropertySet("ColumnWidth", 15);
		vSheetMonth.OlePropertyGet("Columns", WideString("Q")).OlePropertySet("ColumnWidth", 50);

		setBorders(vSheetMonth, nRow, 14);
		setBorders(vSheetMonth, nRow, 15);
		setBorders(vSheetMonth, nRow, 16);
		setBorders(vSheetMonth, nRow, 17);

		setColor(vSheetMonth, nRow, 14, RGBToInt(240, 230, 140));
		setColor(vSheetMonth, nRow, 15, RGBToInt(240, 230, 140));
		setColor(vSheetMonth, nRow, 16, RGBToInt(240, 230, 140));
		setColor(vSheetMonth, nRow, 17, RGBToInt(240, 230, 140));

		ProgressBar1->Max = months.size();
		ProgressBar1->Min = 0;
		for (unsigned int i = 0; i < months.size(); i++) {
			nRow++;
			ProgressBar1->Position = i;
			nSum += months[i].Price;

			vSheetMonth.OlePropertyGet("Cells").OlePropertyGet("Item",nRow,14).OlePropertySet("Value", WideString(months[i].Class));
			vSheetMonth.OlePropertyGet("Cells").OlePropertyGet("Item",nRow,15).OlePropertySet("Value", WideString(months[i].Name));
			vSheetMonth.OlePropertyGet("Cells").OlePropertyGet("Item",nRow,16).OlePropertySet("Value", WideString(months[i].Price));
			vSheetMonth.OlePropertyGet("Cells").OlePropertyGet("Item",nRow,16).OlePropertySet("NumberFormat", WideString(m_strNumberFormat));

			if (months[i].Price < 0) {
				setColor(vSheetMonth, nRow, 16, RGBToInt(240, 230, 140));
			}


			// TODO: check linkt to classification
			// vSheetMonth.OlePropertyGet("Cells").OlePropertyGet("Item",nRow,17).OlePropertySet("Value", WideString(months[i].LinkToClassification.c_str()));

			setBorders(vSheetMonth, nRow, 14);
			setBorders(vSheetMonth, nRow, 15);
			setBorders(vSheetMonth, nRow, 16);
			setBorders(vSheetMonth, nRow, 17);
		}
		nRow++;
		ProgressBar1->Position = 0;

		vSheetMonth.OlePropertyGet("Cells").OlePropertyGet("Item",nRow,14).OlePropertySet("Value", WideString("Итого:"));
		vSheetMonth.OlePropertyGet("Cells").OlePropertyGet("Item",nRow,16).OlePropertySet("Value", WideString(nSum));
		vSheetMonth.OlePropertyGet("Cells").OlePropertyGet("Item",nRow,16).OlePropertySet("NumberFormat", WideString(m_strNumberFormat));
		vSheetMonth.OlePropertyGet("Cells").OlePropertyGet("Item",nRow,17).OlePropertySet("NumberFormat", WideString(m_strNumberFormat));
	}

	Log->Lines->Add("Сохраняю файл...");
	try {
		app.OlePropertySet("DisplayAlerts",false);
		excel.OleProcedure("SaveAs", WideString(m_strFileName.c_str()));
		Log->Lines->Add("Данные сохранены!");
	} catch (...) {
		Log->Lines->Add("Ошибка: Пожалуйста закройте все открытые копии файла и повторите операцию");
	}
    ProgressBar1->Position = 0;
	app.OleProcedure("Quit");
}