Интеграция OpenOffice Calc с 1С 7.7 Ключевые слова: 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.
рабочий код по вставке диаграмм в Calc в нужную позицию и нужных размеров и заполнение их данными
Автор - r_newman
http://community.i-rs.ru/index.php/topic,5832.0.html
В конце треда. Там же ссылка на книгу
"Learn OpenOffice.org Spreadsheet Macro Programming: OOoBasic and Calc automation"
автора
Dr Mark Alexander Bain
These 3 toolboxes help programmers drive the application OpenOffice.org from a VB-like programming language using COM Automation technology:
http://sourceforge.net/project/showfiles.php?group_id=87718&package_id=240562
Браузер объектов UNO
http://sourceforge.net/project/showfiles.php?group_id=87718&package_id=101416
Рекомендуется использовать совместно с OO SDK
http://download.openoffice.org/2.3.0/sdk.html
Работа с ОО из .Net
Подключите сборки cli_basetypes, cli_cppuhelper, cli_types, cli_ure (находятся в каталоге <App>\program\assembly\). Они совместимы с .Net 1.1...3.5
Dim d As unoidl.com.sun.star.uno.XComponentContext = uno.util.Bootstrap.bootstrap
Dim c As unoidl.com.sun.star.lang.XMultiServiceFactory = d.getServiceManager
Dim a As unoidl.com.sun.star.frame.XComponentLoader = c.createInstance("com.sun.star.frame.Desktop")
Dim sv(0) As unoidl.com.sun.star.beans.PropertyValue
Dim n As unoidl.com.sun.star.lang.XComponent = a.loadComponentFromURL("private:factory/scalc", "_blank", 0, sv)
Dim m As unoidl.com.sun.star.sheet.XSpreadsheetDocument
m = n
m.getSheets().getByName("Tabelle1")
http://www.i-rs.ru/article/articleview/144/1/55/
ДокументацияНа Русском
Руководство по Calc
http://authors.i-rs.ru/03%20Calc%20Guide/0300CG-CalcGuide-Ru.pdf
Памятка для перехода с Word Excel (Microsoft Office) на OpenOffice краткая
http://buhcia.narod.ru/ForOpenOffice.zip
Программирование на языке OpenOffice.org Basic
http://authors.i-rs.ru/Basic/OpenOffice.org.BASIC%20Guide.pdf
Перевод книги Andrew Pitonyak "Useful Macro Information For OpenOffice"
http://buhcia.narod.ru/OpenOffice_Macros_rus.odt
FAQ по OpenOffice.org
http://wiki.services.openoffice.org/wiki/Ru/faq
На английском
Руководство Разработчика (> 1100 страниц)
http://api.openoffice.org/docs/DevelopersGuide/DevelopersGuide.pdf
Полная документация пользователя
http://documentation.openoffice.org/manuals/oooauthors2/
Getting Started With Base
http://documentation.openoffice.org/manuals/oooauthors2/0110GS-GettingStartedWithBase.pdf
Руководство программиста по Base
http://www.pitonyak.org/database/AndrewBase.pdf
Шаблоны кода ОО для решения типовых задач:
http://codesnippets.services.openoffice.org/index.xml
OO Tutorials & templates
http://www.kaaredyret.dk/openoffice_links.html
Примеры к книге http://books.google.de/books?id=ZE93AAAACAAJ&dq=isbn:3446404503&as_brr=0
http://www.compurem.de/ooo/Buchbeispiele.zip
http://www.compurem.de/ooo/Vorlagen.zip
Упрощение миграции с MSO
советы по переходу с VBA
http://documentation.openoffice.org/HOW_TO/various_topics/VbaStarBasicXref.pdf
OO Migration Guide
http://documentation.openoffice.org/manuals/oooauthors2/0600MG-MigrationGuide.pdf
Я не хочу связываться с очень сложной моделью ОО и переписывать уже существующий код.
Попытайтесь воспользоваться режимом совместимости с VBA, которая поддержвается сборкой от Инфра-Ресурс (http://download.i-rs.ru/pub/openoffice/)
В книге "Learn OpenOffice.org Spreadsheet Macro Programming: OOoBasic and Calc automation"
есть глава про использование режима VBA.
Dim ooApp
Set oServiceManager = CreateObject("com.sun.star.ServiceManager")
Set oDesktop = oServiceManager.createInstance("com.sun.star.frame.Desktop")
Dim aNoArgs()
Set oCalcDoc = oDesktop.loadComponentFromURL("private:factory/scalc", "_blank", 0, aNoArgs)
Set v = oServiceManager.DefaultContext.getValueByName("/singletons/org.openoffice.vba.theGlobals")
Set ooApp = v.Application
MsgBox ooApp.Version
Set cell = ooApp.ActiveCell
cell.Value = "Hello!"
Set r = ooApp .Range("B1", "B1")
r.Value = "Hi1"
http://wiki.services.openoffice.org/wiki/VBA
http://wiki.services.openoffice.org/wiki/Oovbaapi
http://1c.proclub.ru/modules/mydownloads/personal.php?cid=143&lid=7926
http://community.i-rs.ru/index.php?action=dlattach;topic=6096.0;attach=4431
Microsoft Excel Visual Basic for Applications (VBA) to OpenOffice Calc Basic converter
http://www.business-spreadsheets.com/vba2oo.asp
Библиотека, упрощающая доступ к данным Open Office Calc. Предоставляет automation интерфейс, схожий с интерфейсом Excel.Application, что позволяет использовать созданные для Microsoft Excel продукты в среде OpenOffice.org с минимальными модификациями.
http://triteh.ru/xls1c/index.php
Nice Office Access, который призван упростить достаточно сложную объектную модель ОО
предназначен для разработки приложений ОО на Ява
http://ubion.ion.ag/loesungen/004niceofficeaccess
Библиотеки работы с OpenDocumentAODL для .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.
Office 2007
SDK for Open XML Formats (Beta) - работа с файлами Office 2007 без Office из своих приложений
Требует .Net 3.0. Размер ДЛЛ - 200 Кб.
Все остальное - хороший Help.
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()
Можно установить бесплатный Add-In для среды разработки VBA
http://www.mztools.com/v3/download.aspx
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 |