Книга знаний

1С:Предприятие / Приемы программирования / OLE, COM

Интеграция OpenOffice Calc с 1С 7.7

Управление OpenOffice Calc из 1С 7.7 через UNOАвтор статьи: jbond | Редакторы: Волшебник,
Последняя редакция №16 от 26.09.07 | История
URL: http://kb.mista.ru/article.php?id=180

Ключевые слова: UNO, OpenOffice, Calc, OpenDocument, Array, ODF, OpenXML, Office 2007, Интеграция, Excel


OpenOffice


Основная проблема при работе с 7.7 - это проблема передачи массивов через COM.
Здесь предлагается, вероятно, наилучшее решение этой проблемы.
Оно базируется на идее и коде smаhаrbА на Нью-Территории 1С.

   scr = СоздатьОбъект("MSScriptControl.ScriptControl");
   scr.language = "javascript";
   scr.eval("Массив=new Array()");
   Массив = scr.eval("Массив");
   scr.AddCode("function SetItem(ind,val){Массив[ind]=val}");
   
   ServiceManager=СоздатьОбъект("com.sun.star.ServiceManager");
   scr.AddObject("ServiceManager",ServiceManager);
   Desktop = ServiceManager.createInstance("com.sun.star.frame.Desktop");
   Document = Desktop.LoadComponentFromURL("private:factory/scalc", "_blank", 0, Массив);
   Листы = Document.getSheets();
   Лист = Листы.getByIndex(0);
   Для к = 0 По 10 Цикл
      Лист.getCellByPosition(0,к).value = к;
   КонецЦикла;
   SaveParam = scr.Eval("ServiceManager.Bridge_GetStruct('com.sun.star.beans.PropertyValue')");
   SaveParam.Name = "FilterName";
   SaveParam.Value = "MS Excel 97";
   scr.CodeObject.SetItem(0,SaveParam);
   Document.storeToURL("file:///c:/Test.xls",Массив);


По адресу http://1c.proclub.ru/modules/mydownloads/personal.php?cid=5&lid=6573
можно найти первые наброски по разработке библиотеки классов 1С++ для автоматизации OO.

Очень подробный хелп + примеры по автоматизации OO через UNO можно изучить, скачав SDK:
http://api.openoffice.org/SDK/index.html

Перевод книги Andrew Pitonyak "Useful Macro Information For OpenOffice"
http://buhcia.narod.ru/OpenOffice_Macros_rus.odt

Существует инструмент Nice Office Access, который призван упростить достаточно сложную объектную модель ОО
(но он, похоже, предназначен для разработки прилозений ОО на Ява)
http://ubion.ion.ag/loesungen/004niceofficeaccess

Библиотека, упрощающая доступ к данным Open Office Calc. Предоставляет automation интерфейс, схожий с интерфейсом Excel.Application, что позволяет использовать созданные для Microsoft Excel продукты в среде OpenOffice.org с минимальными модификациями.

http://triteh.ru/xls1c/index.php

Среди библиотек непосредственой работы с OpenDocument можно отметить AODL (для .Net)
http://wiki.services.openoffice.org/wiki/AODL

Пример создания ODS файла с использованием AODL на Visual Basic .Net (2005):
Imports AODL.Document

    Sub ExportODF(ByVal FileName As String)
        'Create new spreadsheet document
        Dim spreadsheetDocument As New SpreadsheetDocuments.SpreadsheetDocument

        If System.IO.File.Exists(FileName) Then
            spreadsheetDocument.Load(FileName)
        Else
            spreadsheetDocument.[New]()
        End If

        'Create a new table

        Dim Jahr As Integer = CInt(JahrToolStripTextBox.Text)
        Dim Monat As Integer = MonatToolStripComboBox.SelectedIndex + 1

        Dim dt As New DateTime(Jahr, Monat, 1)

        Dim table As New Content.Tables.Table(spreadsheetDocument, dt.ToString("MMMM yy"), "")

        With DatenDataGridView
            For rowIndex As Integer = 0 To .RowCount - 1
                For colIndex As Integer = 1 To .ColumnCount - 1
                    Dim cell As Content.Tables.Cell = table.CreateCell()

                    Dim curItem As DataGridViewCell = .Item(colIndex, rowIndex)
                    Dim curValue As Object = curItem.Value

                    If Not IsNothing(curValue) Then
                        If IsNumeric(curValue) Then
                            cell.OfficeValueType = SpreadsheetDocuments.Tables.Style.OfficeValueTypes.Float
                        Else
                            cell.OfficeValueType = SpreadsheetDocuments.Tables.Style.OfficeValueTypes.String
                        End If

                        'cell.CellStyle.CellProperties.Border = AODL.Document.Styles.Border.NormalSolid

                        cell.OfficeValue = curValue.ToString
                    End If
                    table.InsertCellAt(rowIndex + 1, colIndex + 1, cell)
                Next
            Next
        End With
        'Insert table into the spreadsheet document
        spreadsheetDocument.TableCollection.Add(table)
        spreadsheetDocument.SaveTo(FileName)
    End Sub


OO на компьютере не требуется, т.к. происходит непосредственное создание документа ODS.

Существует также библиотека для Ява:
http://wiki.services.openoffice.org/wiki/Odf4j

Office 2007



SDK for Open XML Formats - работа с файлами Office 2007 без Office из своих приложений
Требует .Net. Размер ДЛЛ - 200 Кб. требует .NET 3.0
Все остальное - хороший хелп

http://www.microsoft.com/downloads/details.aspx?FamilyID=ad0b72fb-4a1d-4c52-bdb5-7dd7e816d046&DisplayLang=en

Лабораторные работы по OpenXML
http://www.gotdotnet.ru/Downloads/Examples/493404.aspx

Open XML Explained
http://openxmldeveloper.org/attachment/1970.ashx
http://openxmldeveloper.org/attachment/1690.ashx

Следуюший макрос использует специально оставленную товарищами
из Microsoft возможность бесконечно долгого бесплатного использования Excel 2007.

Сохранение документов отключено (будет выдаваться окно активации).
Но для VBA - разработчика (есть экспорт VBA обьектов) и использования Excel: составил отчет через OLE, распечатал и забыл - будет вполне достаточно.

Dim WExcel
Set WExcel = WScript.CreateObject("Excel.Application")
WExcel.Visible = True
WExcel.Workbooks.Add()


Sun ODF Plugin 1.0 for Microsoft Office
The Sun ODF Plug in for Microsoft Office gives users of Microsoft Word, Excel and Powerpoint the ability to read, edit and save to the ISO-standard Open Document Format. The ODF Plug in is available as a free download from the Sun Download Center (SDLC).

http://javashoplm.sun.com/ECom/docs/Welcome.jsp?StoreId=8&PartDetailId=ODF-WIN-G-F&TransactionId=noreg

Описание | Рубрикатор | Поиск | ТелепатБот | Захваченные статьи | Установки | Форум
© Станислав Митичкин (Волшебник), 2005-2025 | Mista.ru

Яндекс.Метрика