Все записи автора Apa Pacy

Печать твердых копий из OOBase

ООфис  имеет встроенные средства для создания отчетов и они наверное подойдут многим. Но откровенно говоря я склоняюсь к печати документов через программно генерируемые таблицы ООКалк.

Кто еще хочет попробовать вот много кода из которого можно и для себя взять какие-то моменты. Главное собственно вызвать ООКалк с пустым документом, а по прочим вопросам документации достаточно.

Sub PrintNZP()

MsgBox "Закройте текущее сообщение и дождитесь сообщение <<Обработка документа окончена>>"

Dim oNDoc, oNSheets, oNSheet

oNDoc = StarDesktop.loadComponentFromURL( _
"private:factory/scalc", "_blank", 0, Array() )
oNSheets = oNDoc.getSheets()
oNSheet = oNSheets.getByIndex(0)


Dim sCurrentKod As String
Dim Connection As Variant
Dim Statement As Variant
Dim ResultSet As Variant
Dim UpdateStatement As Variant
Dim sKod As String
Dim dPlatmin As Double
Dim dCts As Double
Dim dPlatkop As Double
Dim iCountErr As Integer

If FormDoc_det.isModified Then
FormDoc_det().UpdateRow()
End If

GlobalScope.BasicLibraries.loadLibrary("aovc")
sCurrentKod = FormDoc_h().Columns.getByName("Kod").String
Connection = aovc.GetConnection()
Statement = Connection.CreateStatement()
ResultSet = Statement.ExecuteQuery("SELECT doc_det.*, doc_det.kol * doc_det.nv AS min, doc_det.kol * doc_det.rc / 100 AS grn, (SELECT DISTINCT name FROM cennic AS c WHERE c.kod = doc_det.koddet) AS namedet, (SELECT DISTINCT i.name FROM izdel AS i WHERE i.kod = doc_det.kodiz) AS nameiz FROM dbo.doc_det AS doc_det where doc_det.kod=" & sCurrentKod & " order by kod")

Dim iCounter as Integer
Dim I As Integer
oNSheet.GetCellByPosition(7,0).string = "А К Т"
oNSheet.GetCellByPosition(3,1).string = "инвентаризации незавершенного производства по цеху 16 на 1-е"
oNSheet.GetCellByPosition(7,0).CharHeight = 14
oNSheet.GetCellByPosition(3,1).CharHeight = 14
oNSheet.GetCellByPosition(3,1).string = FormDoc_h.Columns.GetByName("prim").String
oNSheet.GetCellByPosition(0,2).string = "№ пп"
oNSheet.GetCellRangeByPosition(0,2,0,3).Merge(True)
oNSheet.GetCellByPosition(0,2).Columns.GetByIndex(0).Width = "700"
oNSheet.GetCellByPosition(0,2).isTextWrapped = True
oNSheet.GetCellByPosition(0,2).HoriJustify = 2
oNSheet.GetCellByPosition(0,2).VertJustify = 2

oNSheet.GetCellByPosition(1,2).string = "Наименование изделий, деталей и узлов"
oNSheet.GetCellByPosition(1,2).Columns.GetByIndex(0).Width = "4200"
oNSheet.GetCellRangeByPosition(1,2,1,3).Merge(True)
oNSheet.GetCellByPosition(1,2).isTextWrapped = True
oNSheet.GetCellByPosition(1,2).HoriJustify = 2
oNSheet.GetCellByPosition(1,2).VertJustify = 2

oNSheet.GetCellByPosition(2, 2).string = "№№ деталей или узлов"
oNSheet.GetCellByPosition(2,2).isTextWrapped = True
oNSheet.GetCellRangeByPosition(2,2,2,3).Merge(True)
oNSheet.GetCellByPosition(2,2).HoriJustify = 2
oNSheet.GetCellByPosition(2,2).VertJustify = 2
oNSheet.GetCellByPosition(2,2).Columns.GetByIndex(0).Width = "1800"

oNSheet.GetCellByPosition(3, 2).string = "Ед. изм."
oNSheet.GetCellByPosition(3,2).isTextWrapped = True
oNSheet.GetCellRangeByPosition(3,2,3,3).Merge(True)
oNSheet.GetCellByPosition(3,2).HoriJustify = 2
oNSheet.GetCellByPosition(3,2).VertJustify = 2
oNSheet.GetCellByPosition(3,2).Columns.GetByIndex(0).Width = "1000"

oNSheet.GetCellByPosition(4, 2).string = "№ послед-ней закончен-ной операции"
'oNSheet.GetCellByPosition(4,2).isTextWrapped = True
oNSheet.GetCellRangeByPosition(4,2,4,3).isTextWrapped = True
oNSheet.GetCellRangeByPosition(4,2,4,3).Merge(True)
oNSheet.GetCellByPosition(4,2).HoriJustify = 2
oNSheet.GetCellByPosition(4,2).VertJustify = 2
oNSheet.GetCellByPosition(4,2).Columns.GetByIndex(0).Width = "2000"

oNSheet.GetCellByPosition(5, 2).string = "Книж-ный оста-ток"
oNSheet.GetCellByPosition(5,2).isTextWrapped = True
oNSheet.GetCellRangeByPosition(5,2,5,3).Merge(True)
oNSheet.GetCellByPosition(5,2).HoriJustify = 2
oNSheet.GetCellByPosition(5,2).VertJustify = 2
oNSheet.GetCellByPosition(5,2).Columns.GetByIndex(0).Width = "1800"


oNSheet.GetCellByPosition(6, 2).string = "Факти-ческое нали-чие"
oNSheet.GetCellByPosition(6,2).isTextWrapped = True
oNSheet.GetCellRangeByPosition(6,2,6,3).Merge(True)
oNSheet.GetCellByPosition(6,2).HoriJustify = 2
oNSheet.GetCellByPosition(6,2).VertJustify = 2
oNSheet.GetCellByPosition(6,2).Columns.GetByIndex(0).Width = "1400"

oNSheet.GetCellByPosition(7, 2).string = "Результат"
oNSheet.GetCellByPosition(7,2).isTextWrapped = True
oNSheet.GetCellRangeByPosition(7,2,8,2).Merge(True)
oNSheet.GetCellByPosition(7,2).HoriJustify = 2
oNSheet.GetCellByPosition(7,2).VertJustify = 2
'oNSheet.GetCellByPosition(7,2).Columns.GetByIndex(0).Width = "1800"


oNSheet.GetCellByPosition(7, 3).string = "Из-лиш-ки"
oNSheet.GetCellByPosition(7,3).isTextWrapped = True
oNSheet.GetCellByPosition(7,3).HoriJustify = 2
oNSheet.GetCellByPosition(7,3).VertJustify = 2
oNSheet.GetCellByPosition(7,3).Columns.GetByIndex(0).Width = "1100"

oNSheet.GetCellByPosition(8, 3).string = "Недо-стача"
oNSheet.GetCellByPosition(8,3).isTextWrapped = True
oNSheet.GetCellByPosition(8,3).HoriJustify = 2
oNSheet.GetCellByPosition(8,3).VertJustify = 2
oNSheet.GetCellByPosition(8,3).Columns.GetByIndex(0).Width = "1100"


oNSheet.GetCellByPosition(9, 2).string = "Стоимость материала"
oNSheet.GetCellByPosition(9,2).isTextWrapped = True
oNSheet.GetCellRangeByPosition(9,2,10,2).Merge(True)
oNSheet.GetCellByPosition(9,2).HoriJustify = 2
oNSheet.GetCellByPosition(9,2).VertJustify = 2
'oNSheet.GetCellByPosition(9,2).Columns.GetByIndex(0).Width = "1800"


oNSheet.GetCellByPosition(9, 3).string = "На единицу"
oNSheet.GetCellByPosition(9,3).isTextWrapped = True
oNSheet.GetCellByPosition(9,3).HoriJustify = 2
oNSheet.GetCellByPosition(9,3).VertJustify = 2
oNSheet.GetCellByPosition(9,3).Columns.GetByIndex(0).Width = "2400"

oNSheet.GetCellByPosition(10, 3).string = "На все количе-ство"
oNSheet.GetCellByPosition(10,3).isTextWrapped = True
oNSheet.GetCellByPosition(10,3).HoriJustify = 2
oNSheet.GetCellByPosition(10,3).VertJustify = 2
oNSheet.GetCellByPosition(10,3).Columns.GetByIndex(0).Width = "1900"


oNSheet.GetCellByPosition(11, 2).string = "Стоимость зарплаты"
oNSheet.GetCellByPosition(11,2).isTextWrapped = True
oNSheet.GetCellRangeByPosition(11,2,12,2).Merge(True)
oNSheet.GetCellByPosition(11,2).HoriJustify = 2
oNSheet.GetCellByPosition(11,2).VertJustify = 2

oNSheet.GetCellByPosition(11, 3).string = "На единицу"
oNSheet.GetCellByPosition(11,3).isTextWrapped = True
oNSheet.GetCellByPosition(11,3).HoriJustify = 2
oNSheet.GetCellByPosition(11,3).VertJustify = 2
oNSheet.GetCellByPosition(11,3).Columns.GetByIndex(0).Width = "2400"

oNSheet.GetCellByPosition(12, 3).string = "На все количе-ство"
oNSheet.GetCellByPosition(12,3).isTextWrapped = True
oNSheet.GetCellByPosition(12,3).HoriJustify = 2
oNSheet.GetCellByPosition(12,3).VertJustify = 2
oNSheet.GetCellByPosition(12,3).Columns.GetByIndex(0).Width = "1600"

oNSheet.GetCellByPosition(13, 2).string = "Цехо-вые рас-ходы _____%"
oNSheet.GetCellByPosition(13,2).isTextWrapped = True
oNSheet.GetCellRangeByPosition(13,2,13,3).Merge(True)
oNSheet.GetCellByPosition(13,2).HoriJustify = 2
oNSheet.GetCellByPosition(13,2).VertJustify = 2
oNSheet.GetCellByPosition(13,2).Columns.GetByIndex(0).Width = "1600"

oNSheet.GetCellByPosition(14, 2).string = "Обще-завод-ские рас-ходы _____%"
oNSheet.GetCellByPosition(14,2).isTextWrapped = True
oNSheet.GetCellRangeByPosition(14,2,14,3).Merge(True)
oNSheet.GetCellByPosition(14,2).HoriJustify = 2
oNSheet.GetCellByPosition(14,2).VertJustify = 2
oNSheet.GetCellByPosition(14,2).Columns.GetByIndex(0).Width = "1600"

oNSheet.GetCellByPosition(15, 2).string = "Всего завод-ская себе-стои-мость"
oNSheet.GetCellByPosition(15,2).isTextWrapped = True
oNSheet.GetCellRangeByPosition(15,2,15,3).Merge(True)
oNSheet.GetCellByPosition(15,2).HoriJustify = 2
oNSheet.GetCellByPosition(15,2).VertJustify = 2
oNSheet.GetCellByPosition(15,2).Columns.GetByIndex(0).Width = "1800"



Dim BasicBorder as New com.sun.star.table.BorderLine
Dim BasicBorder0 as New com.sun.star.table.BorderLine
Dim oBorder As Object
oBorder = oNSheet.getCellRangeByPosition(0,2,15,4).TableBorder
rem Werte für einen einfachen Rand
BasicBorder.Color = RGB(0, 0, 0)
BasicBorder.InnerLineWidth = 20
BasicBorder.OuterLineWidth = 20
BasicBorder.LineDistance =0

BasicBorder0.Color = RGB(0, 0, 0)
BasicBorder0.InnerLineWidth = 100
BasicBorder0.OuterLineWidth = 0
BasicBorder0.LineDistance = 0

oBorder.LeftLine = BasicBorder
oBorder.TopLine = BasicBorder
oBorder.RightLine = BasicBorder
oBorder.BottomLine = BasicBorder
oBorder.HorizontalLine = BasicBorder
oBorder.VerticalLine = BasicBorder
oNSheet.getCellRangeByPosition(0,2,15,4).TableBorder = oBorder

Dim currentKodDet As Long
Dim currentKodIz As Long
Dim Npp As Long
Dim Total As Long
Dim Count As Long

currentKodDet = -9999
currentKodIz = -9999
Npp=0
Total = 0
Count = 0

iCounter = 3

While ResultSet.Next

If ResultSet.Columns.getByName("kol").Long = 0 Then
GOTO lNext
End If

oBorder = oNSheet.getCellRangeByPosition(0,iCounter,15,iCounter).TableBorder
oBorder.LeftLine = BasicBorder
oBorder.TopLine = BasicBorder
oBorder.RightLine = BasicBorder
oBorder.BottomLine = BasicBorder
oBorder.HorizontalLine = BasicBorder
oBorder.VerticalLine = BasicBorder
oNSheet.getCellRangeByPosition(0,iCounter,15,iCounter).TableBorder = oBorder

If currentKodDet <> ResultSet.Columns.getByName("koddet").Long OR currentKodIz <> ResultSet.Columns.getByName("kodiz").Long Then

If Count > 1 Then
oNSheet.GetCellByPosition(5, iCounter).value = Total
oNSheet.GetCellByPosition(6, iCounter).value = Total
oBorder = oNSheet.getCellRangeByPosition(4, iCounter,6,iCounter).TableBorder
oBorder.TopLine = BasicBorder0
oNSheet.getCellRangeByPosition(4, iCounter,6,iCounter).TableBorder = oBorder
iCounter = iCounter + 1
End If

oBorder = oNSheet.getCellRangeByPosition(0,iCounter,15,iCounter).TableBorder
oBorder.LeftLine = BasicBorder
oBorder.TopLine = BasicBorder
oBorder.RightLine = BasicBorder
oBorder.BottomLine = BasicBorder
oBorder.HorizontalLine = BasicBorder
oBorder.VerticalLine = BasicBorder
oNSheet.getCellRangeByPosition(0,iCounter,15,iCounter).TableBorder = oBorder

currentKodDet = ResultSet.Columns.getByName("koddet").Long
Npp = Npp + 1
Total = 0
Count = 0
iCounter = iCounter + 1
End If

If currentKodIz <> ResultSet.Columns.getByName("kodiz").Long Then
oBorder = oNSheet.getCellRangeByPosition(0,iCounter,15,iCounter).TableBorder
oBorder.LeftLine = BasicBorder
oBorder.TopLine = BasicBorder0
oBorder.RightLine = BasicBorder
oBorder.BottomLine = BasicBorder
oBorder.HorizontalLine = BasicBorder
oBorder.VerticalLine = BasicBorder
oNSheet.getCellRangeByPosition(0,iCounter,15,iCounter).TableBorder = oBorder
currentKodIz = ResultSet.Columns.getByName("kodiz").Long
Npp = 1
oNSheet.GetCellByPosition(1, iCounter).string = Trim(ResultSet.Columns.getByName("nameiz").String)
oNSheet.GetCellByPosition(1, iCounter).CharHeight = 20
iCounter = iCounter + 1
EndIf

oBorder = oNSheet.getCellRangeByPosition(0,iCounter,15,iCounter).TableBorder
oBorder.LeftLine = BasicBorder
oBorder.TopLine = BasicBorder
oBorder.RightLine = BasicBorder
oBorder.BottomLine = BasicBorder
oBorder.HorizontalLine = BasicBorder
oBorder.VerticalLine = BasicBorder
oNSheet.getCellRangeByPosition(0,iCounter,15,iCounter).TableBorder = oBorder


Count = Count + 1

If Count = 1 Then
oNSheet.GetCellByPosition(1, iCounter).string = Trim(ResultSet.Columns.getByName("namedet").String) & Rem97(ResultSet.Columns.getByName("naz").Long)
oNSheet.GetCellByPosition(0, iCounter).value = Npp
End If

oNSheet.GetCellByPosition(4, iCounter).String = sNop(ResultSet.Columns.getByName("nop").Long)
oNSheet.GetCellByPosition(5, iCounter).value = ResultSet.Columns.getByName("kol").Long
oNSheet.GetCellByPosition(6, iCounter).value = ResultSet.Columns.getByName("kol").Long

If ResultSet.Columns.getByName("nv").Double > 0 Then
oNSheet.GetCellByPosition(2, iCounter).value = ResultSet.Columns.getByName("nv").Double
oNSheet.GetCellByPosition(11, iCounter).value = ResultSet.Columns.getByName("rc").Double
Else
oNSheet.GetCellByPosition(11, iCounter).string = " - "
End If

Total = Total + ResultSet.Columns.getByName("kol").Long

iCounter = iCounter + 1
lNext: REM
Wend
If Count > 1 Then
oBorder = oNSheet.getCellRangeByPosition(0,iCounter,15,iCounter).TableBorder
oBorder.LeftLine = BasicBorder
oBorder.TopLine = BasicBorder
oBorder.RightLine = BasicBorder
oBorder.BottomLine = BasicBorder
oBorder.HorizontalLine = BasicBorder
oBorder.VerticalLine = BasicBorder
oNSheet.getCellRangeByPosition(0,iCounter,15,iCounter).TableBorder = oBorder
oNSheet.GetCellByPosition(5, iCounter).value = Total
oNSheet.GetCellByPosition(6, iCounter).value = Total
oBorder = oNSheet.getCellRangeByPosition(4, iCounter,6,iCounter).TableBorder
oBorder.TopLine = BasicBorder0
oNSheet.getCellRangeByPosition(4, iCounter,6,iCounter).TableBorder = oBorder
iCounter = iCounter + 1
End If
oBorder = oNSheet.getCellRangeByPosition(0,iCounter,15,iCounter).TableBorder
oBorder.LeftLine = BasicBorder
oBorder.TopLine = BasicBorder
oBorder.RightLine = BasicBorder
oBorder.BottomLine = BasicBorder0
oBorder.HorizontalLine = BasicBorder
oBorder.VerticalLine = BasicBorder
oNSheet.getCellRangeByPosition(0,iCounter,15,iCounter).TableBorder = oBorder


oNSheet.GetCellByPosition(1, iCounter + 1).string = "==========================================="
MsgBox "Обработка документа окончена"

End Sub


Печать твердых копий из OOBase

ООфис  имеет встроенные средства для создания отчетов и они наверное подойдут многим. Но откровенно говоря я склоняюсь к печати документов через программно генерируемые таблицы ООКалк.

Кто еще хочет попробовать вот много кода из которого можно и для себя взять какие-то моменты. Главное собственно вызвать ООКалк с пустым документом, а по прочим вопросам документации достаточно.

Sub PrintNZP()

MsgBox "Закройте текущее сообщение и дождитесь сообщение <<Обработка документа окончена>>"

Dim oNDoc, oNSheets, oNSheet

oNDoc = StarDesktop.loadComponentFromURL( _
"private:factory/scalc", "_blank", 0, Array() )
oNSheets = oNDoc.getSheets()
oNSheet = oNSheets.getByIndex(0)


Dim sCurrentKod As String
Dim Connection As Variant
Dim Statement As Variant
Dim ResultSet As Variant
Dim UpdateStatement As Variant
Dim sKod As String
Dim dPlatmin As Double
Dim dCts As Double
Dim dPlatkop As Double
Dim iCountErr As Integer

If FormDoc_det.isModified Then
FormDoc_det().UpdateRow()
End If

GlobalScope.BasicLibraries.loadLibrary("aovc")
sCurrentKod = FormDoc_h().Columns.getByName("Kod").String
Connection = aovc.GetConnection()
Statement = Connection.CreateStatement()
ResultSet = Statement.ExecuteQuery("SELECT doc_det.*, doc_det.kol * doc_det.nv AS min, doc_det.kol * doc_det.rc / 100 AS grn, (SELECT DISTINCT name FROM cennic AS c WHERE c.kod = doc_det.koddet) AS namedet, (SELECT DISTINCT i.name FROM izdel AS i WHERE i.kod = doc_det.kodiz) AS nameiz FROM dbo.doc_det AS doc_det where doc_det.kod=" & sCurrentKod & " order by kod")

Dim iCounter as Integer
Dim I As Integer
oNSheet.GetCellByPosition(7,0).string = "А К Т"
oNSheet.GetCellByPosition(3,1).string = "инвентаризации незавершенного производства по цеху 16 на 1-е"
oNSheet.GetCellByPosition(7,0).CharHeight = 14
oNSheet.GetCellByPosition(3,1).CharHeight = 14
oNSheet.GetCellByPosition(3,1).string = FormDoc_h.Columns.GetByName("prim").String
oNSheet.GetCellByPosition(0,2).string = "№ пп"
oNSheet.GetCellRangeByPosition(0,2,0,3).Merge(True)
oNSheet.GetCellByPosition(0,2).Columns.GetByIndex(0).Width = "700"
oNSheet.GetCellByPosition(0,2).isTextWrapped = True
oNSheet.GetCellByPosition(0,2).HoriJustify = 2
oNSheet.GetCellByPosition(0,2).VertJustify = 2

oNSheet.GetCellByPosition(1,2).string = "Наименование изделий, деталей и узлов"
oNSheet.GetCellByPosition(1,2).Columns.GetByIndex(0).Width = "4200"
oNSheet.GetCellRangeByPosition(1,2,1,3).Merge(True)
oNSheet.GetCellByPosition(1,2).isTextWrapped = True
oNSheet.GetCellByPosition(1,2).HoriJustify = 2
oNSheet.GetCellByPosition(1,2).VertJustify = 2

oNSheet.GetCellByPosition(2, 2).string = "№№ деталей или узлов"
oNSheet.GetCellByPosition(2,2).isTextWrapped = True
oNSheet.GetCellRangeByPosition(2,2,2,3).Merge(True)
oNSheet.GetCellByPosition(2,2).HoriJustify = 2
oNSheet.GetCellByPosition(2,2).VertJustify = 2
oNSheet.GetCellByPosition(2,2).Columns.GetByIndex(0).Width = "1800"

oNSheet.GetCellByPosition(3, 2).string = "Ед. изм."
oNSheet.GetCellByPosition(3,2).isTextWrapped = True
oNSheet.GetCellRangeByPosition(3,2,3,3).Merge(True)
oNSheet.GetCellByPosition(3,2).HoriJustify = 2
oNSheet.GetCellByPosition(3,2).VertJustify = 2
oNSheet.GetCellByPosition(3,2).Columns.GetByIndex(0).Width = "1000"

oNSheet.GetCellByPosition(4, 2).string = "№ послед-ней закончен-ной операции"
'oNSheet.GetCellByPosition(4,2).isTextWrapped = True
oNSheet.GetCellRangeByPosition(4,2,4,3).isTextWrapped = True
oNSheet.GetCellRangeByPosition(4,2,4,3).Merge(True)
oNSheet.GetCellByPosition(4,2).HoriJustify = 2
oNSheet.GetCellByPosition(4,2).VertJustify = 2
oNSheet.GetCellByPosition(4,2).Columns.GetByIndex(0).Width = "2000"

oNSheet.GetCellByPosition(5, 2).string = "Книж-ный оста-ток"
oNSheet.GetCellByPosition(5,2).isTextWrapped = True
oNSheet.GetCellRangeByPosition(5,2,5,3).Merge(True)
oNSheet.GetCellByPosition(5,2).HoriJustify = 2
oNSheet.GetCellByPosition(5,2).VertJustify = 2
oNSheet.GetCellByPosition(5,2).Columns.GetByIndex(0).Width = "1800"


oNSheet.GetCellByPosition(6, 2).string = "Факти-ческое нали-чие"
oNSheet.GetCellByPosition(6,2).isTextWrapped = True
oNSheet.GetCellRangeByPosition(6,2,6,3).Merge(True)
oNSheet.GetCellByPosition(6,2).HoriJustify = 2
oNSheet.GetCellByPosition(6,2).VertJustify = 2
oNSheet.GetCellByPosition(6,2).Columns.GetByIndex(0).Width = "1400"

oNSheet.GetCellByPosition(7, 2).string = "Результат"
oNSheet.GetCellByPosition(7,2).isTextWrapped = True
oNSheet.GetCellRangeByPosition(7,2,8,2).Merge(True)
oNSheet.GetCellByPosition(7,2).HoriJustify = 2
oNSheet.GetCellByPosition(7,2).VertJustify = 2
'oNSheet.GetCellByPosition(7,2).Columns.GetByIndex(0).Width = "1800"


oNSheet.GetCellByPosition(7, 3).string = "Из-лиш-ки"
oNSheet.GetCellByPosition(7,3).isTextWrapped = True
oNSheet.GetCellByPosition(7,3).HoriJustify = 2
oNSheet.GetCellByPosition(7,3).VertJustify = 2
oNSheet.GetCellByPosition(7,3).Columns.GetByIndex(0).Width = "1100"

oNSheet.GetCellByPosition(8, 3).string = "Недо-стача"
oNSheet.GetCellByPosition(8,3).isTextWrapped = True
oNSheet.GetCellByPosition(8,3).HoriJustify = 2
oNSheet.GetCellByPosition(8,3).VertJustify = 2
oNSheet.GetCellByPosition(8,3).Columns.GetByIndex(0).Width = "1100"


oNSheet.GetCellByPosition(9, 2).string = "Стоимость материала"
oNSheet.GetCellByPosition(9,2).isTextWrapped = True
oNSheet.GetCellRangeByPosition(9,2,10,2).Merge(True)
oNSheet.GetCellByPosition(9,2).HoriJustify = 2
oNSheet.GetCellByPosition(9,2).VertJustify = 2
'oNSheet.GetCellByPosition(9,2).Columns.GetByIndex(0).Width = "1800"


oNSheet.GetCellByPosition(9, 3).string = "На единицу"
oNSheet.GetCellByPosition(9,3).isTextWrapped = True
oNSheet.GetCellByPosition(9,3).HoriJustify = 2
oNSheet.GetCellByPosition(9,3).VertJustify = 2
oNSheet.GetCellByPosition(9,3).Columns.GetByIndex(0).Width = "2400"

oNSheet.GetCellByPosition(10, 3).string = "На все количе-ство"
oNSheet.GetCellByPosition(10,3).isTextWrapped = True
oNSheet.GetCellByPosition(10,3).HoriJustify = 2
oNSheet.GetCellByPosition(10,3).VertJustify = 2
oNSheet.GetCellByPosition(10,3).Columns.GetByIndex(0).Width = "1900"


oNSheet.GetCellByPosition(11, 2).string = "Стоимость зарплаты"
oNSheet.GetCellByPosition(11,2).isTextWrapped = True
oNSheet.GetCellRangeByPosition(11,2,12,2).Merge(True)
oNSheet.GetCellByPosition(11,2).HoriJustify = 2
oNSheet.GetCellByPosition(11,2).VertJustify = 2

oNSheet.GetCellByPosition(11, 3).string = "На единицу"
oNSheet.GetCellByPosition(11,3).isTextWrapped = True
oNSheet.GetCellByPosition(11,3).HoriJustify = 2
oNSheet.GetCellByPosition(11,3).VertJustify = 2
oNSheet.GetCellByPosition(11,3).Columns.GetByIndex(0).Width = "2400"

oNSheet.GetCellByPosition(12, 3).string = "На все количе-ство"
oNSheet.GetCellByPosition(12,3).isTextWrapped = True
oNSheet.GetCellByPosition(12,3).HoriJustify = 2
oNSheet.GetCellByPosition(12,3).VertJustify = 2
oNSheet.GetCellByPosition(12,3).Columns.GetByIndex(0).Width = "1600"

oNSheet.GetCellByPosition(13, 2).string = "Цехо-вые рас-ходы _____%"
oNSheet.GetCellByPosition(13,2).isTextWrapped = True
oNSheet.GetCellRangeByPosition(13,2,13,3).Merge(True)
oNSheet.GetCellByPosition(13,2).HoriJustify = 2
oNSheet.GetCellByPosition(13,2).VertJustify = 2
oNSheet.GetCellByPosition(13,2).Columns.GetByIndex(0).Width = "1600"

oNSheet.GetCellByPosition(14, 2).string = "Обще-завод-ские рас-ходы _____%"
oNSheet.GetCellByPosition(14,2).isTextWrapped = True
oNSheet.GetCellRangeByPosition(14,2,14,3).Merge(True)
oNSheet.GetCellByPosition(14,2).HoriJustify = 2
oNSheet.GetCellByPosition(14,2).VertJustify = 2
oNSheet.GetCellByPosition(14,2).Columns.GetByIndex(0).Width = "1600"

oNSheet.GetCellByPosition(15, 2).string = "Всего завод-ская себе-стои-мость"
oNSheet.GetCellByPosition(15,2).isTextWrapped = True
oNSheet.GetCellRangeByPosition(15,2,15,3).Merge(True)
oNSheet.GetCellByPosition(15,2).HoriJustify = 2
oNSheet.GetCellByPosition(15,2).VertJustify = 2
oNSheet.GetCellByPosition(15,2).Columns.GetByIndex(0).Width = "1800"



Dim BasicBorder as New com.sun.star.table.BorderLine
Dim BasicBorder0 as New com.sun.star.table.BorderLine
Dim oBorder As Object
oBorder = oNSheet.getCellRangeByPosition(0,2,15,4).TableBorder
rem Werte für einen einfachen Rand
BasicBorder.Color = RGB(0, 0, 0)
BasicBorder.InnerLineWidth = 20
BasicBorder.OuterLineWidth = 20
BasicBorder.LineDistance =0

BasicBorder0.Color = RGB(0, 0, 0)
BasicBorder0.InnerLineWidth = 100
BasicBorder0.OuterLineWidth = 0
BasicBorder0.LineDistance = 0

oBorder.LeftLine = BasicBorder
oBorder.TopLine = BasicBorder
oBorder.RightLine = BasicBorder
oBorder.BottomLine = BasicBorder
oBorder.HorizontalLine = BasicBorder
oBorder.VerticalLine = BasicBorder
oNSheet.getCellRangeByPosition(0,2,15,4).TableBorder = oBorder

Dim currentKodDet As Long
Dim currentKodIz As Long
Dim Npp As Long
Dim Total As Long
Dim Count As Long

currentKodDet = -9999
currentKodIz = -9999
Npp=0
Total = 0
Count = 0

iCounter = 3

While ResultSet.Next

If ResultSet.Columns.getByName("kol").Long = 0 Then
GOTO lNext
End If

oBorder = oNSheet.getCellRangeByPosition(0,iCounter,15,iCounter).TableBorder
oBorder.LeftLine = BasicBorder
oBorder.TopLine = BasicBorder
oBorder.RightLine = BasicBorder
oBorder.BottomLine = BasicBorder
oBorder.HorizontalLine = BasicBorder
oBorder.VerticalLine = BasicBorder
oNSheet.getCellRangeByPosition(0,iCounter,15,iCounter).TableBorder = oBorder

If currentKodDet <> ResultSet.Columns.getByName("koddet").Long OR currentKodIz <> ResultSet.Columns.getByName("kodiz").Long Then

If Count > 1 Then
oNSheet.GetCellByPosition(5, iCounter).value = Total
oNSheet.GetCellByPosition(6, iCounter).value = Total
oBorder = oNSheet.getCellRangeByPosition(4, iCounter,6,iCounter).TableBorder
oBorder.TopLine = BasicBorder0
oNSheet.getCellRangeByPosition(4, iCounter,6,iCounter).TableBorder = oBorder
iCounter = iCounter + 1
End If

oBorder = oNSheet.getCellRangeByPosition(0,iCounter,15,iCounter).TableBorder
oBorder.LeftLine = BasicBorder
oBorder.TopLine = BasicBorder
oBorder.RightLine = BasicBorder
oBorder.BottomLine = BasicBorder
oBorder.HorizontalLine = BasicBorder
oBorder.VerticalLine = BasicBorder
oNSheet.getCellRangeByPosition(0,iCounter,15,iCounter).TableBorder = oBorder

currentKodDet = ResultSet.Columns.getByName("koddet").Long
Npp = Npp + 1
Total = 0
Count = 0
iCounter = iCounter + 1
End If

If currentKodIz <> ResultSet.Columns.getByName("kodiz").Long Then
oBorder = oNSheet.getCellRangeByPosition(0,iCounter,15,iCounter).TableBorder
oBorder.LeftLine = BasicBorder
oBorder.TopLine = BasicBorder0
oBorder.RightLine = BasicBorder
oBorder.BottomLine = BasicBorder
oBorder.HorizontalLine = BasicBorder
oBorder.VerticalLine = BasicBorder
oNSheet.getCellRangeByPosition(0,iCounter,15,iCounter).TableBorder = oBorder
currentKodIz = ResultSet.Columns.getByName("kodiz").Long
Npp = 1
oNSheet.GetCellByPosition(1, iCounter).string = Trim(ResultSet.Columns.getByName("nameiz").String)
oNSheet.GetCellByPosition(1, iCounter).CharHeight = 20
iCounter = iCounter + 1
EndIf

oBorder = oNSheet.getCellRangeByPosition(0,iCounter,15,iCounter).TableBorder
oBorder.LeftLine = BasicBorder
oBorder.TopLine = BasicBorder
oBorder.RightLine = BasicBorder
oBorder.BottomLine = BasicBorder
oBorder.HorizontalLine = BasicBorder
oBorder.VerticalLine = BasicBorder
oNSheet.getCellRangeByPosition(0,iCounter,15,iCounter).TableBorder = oBorder


Count = Count + 1

If Count = 1 Then
oNSheet.GetCellByPosition(1, iCounter).string = Trim(ResultSet.Columns.getByName("namedet").String) & Rem97(ResultSet.Columns.getByName("naz").Long)
oNSheet.GetCellByPosition(0, iCounter).value = Npp
End If

oNSheet.GetCellByPosition(4, iCounter).String = sNop(ResultSet.Columns.getByName("nop").Long)
oNSheet.GetCellByPosition(5, iCounter).value = ResultSet.Columns.getByName("kol").Long
oNSheet.GetCellByPosition(6, iCounter).value = ResultSet.Columns.getByName("kol").Long

If ResultSet.Columns.getByName("nv").Double > 0 Then
oNSheet.GetCellByPosition(2, iCounter).value = ResultSet.Columns.getByName("nv").Double
oNSheet.GetCellByPosition(11, iCounter).value = ResultSet.Columns.getByName("rc").Double
Else
oNSheet.GetCellByPosition(11, iCounter).string = " - "
End If

Total = Total + ResultSet.Columns.getByName("kol").Long

iCounter = iCounter + 1
lNext: REM
Wend
If Count > 1 Then
oBorder = oNSheet.getCellRangeByPosition(0,iCounter,15,iCounter).TableBorder
oBorder.LeftLine = BasicBorder
oBorder.TopLine = BasicBorder
oBorder.RightLine = BasicBorder
oBorder.BottomLine = BasicBorder
oBorder.HorizontalLine = BasicBorder
oBorder.VerticalLine = BasicBorder
oNSheet.getCellRangeByPosition(0,iCounter,15,iCounter).TableBorder = oBorder
oNSheet.GetCellByPosition(5, iCounter).value = Total
oNSheet.GetCellByPosition(6, iCounter).value = Total
oBorder = oNSheet.getCellRangeByPosition(4, iCounter,6,iCounter).TableBorder
oBorder.TopLine = BasicBorder0
oNSheet.getCellRangeByPosition(4, iCounter,6,iCounter).TableBorder = oBorder
iCounter = iCounter + 1
End If
oBorder = oNSheet.getCellRangeByPosition(0,iCounter,15,iCounter).TableBorder
oBorder.LeftLine = BasicBorder
oBorder.TopLine = BasicBorder
oBorder.RightLine = BasicBorder
oBorder.BottomLine = BasicBorder0
oBorder.HorizontalLine = BasicBorder
oBorder.VerticalLine = BasicBorder
oNSheet.getCellRangeByPosition(0,iCounter,15,iCounter).TableBorder = oBorder


oNSheet.GetCellByPosition(1, iCounter + 1).string = "==========================================="
MsgBox "Обработка документа окончена"

End Sub


OOBase Basic

Спасибо за включение ссылки на мои заметки в Вики русскоязычного форума ООо http://wiki.forumooo.ru/wiki/%D0%9F%D0%BE%D0%BB%D0%B5%D0%B7%D0%BD%D1%8B%D0%B5_%D1%81%D1%81%D1%8B%D0%BB%D0%BA%D0%B8 (Сразу замечу, что не имел к этому никакого отношения - просто пытался старательно выполнять свою работу). Понял, что не хватает собственно файла с моими наработками. Вот он с Виртуального Диска Гуугла:
 
https://drive.google.com/file/d/0B1CrvL0JhNFeeFBJWWJ4TGZra1U/view?usp=sharing

OOBase Basic

Спасибо за включение ссылки на мои заметки в Вики русскоязычного форума ООо http://wiki.forumooo.ru/wiki/%D0%9F%D0%BE%D0%BB%D0%B5%D0%B7%D0%BD%D1%8B%D0%B5_%D1%81%D1%81%D1%8B%D0%BB%D0%BA%D0%B8 (Сразу замечу, что не имел к этому никакого отношения - просто пытался старательно выполнять свою работу). Понял, что не хватает собственно файла с моими наработками. Вот он с Виртуального Диска Гуугла:
 
https://drive.google.com/file/d/0B1CrvL0JhNFeeFBJWWJ4TGZra1U/view?usp=sharing
Без рубрики

OpenOfficeBase custom database combobox

Как я и обещал в одном из самых первых сообщений, собирался реализовать компонент combobox.

Зачем? Если есть встроенный. Встроенный есть и встроенного нет. То есть есть но не совсем тот.

 Встроенный DatabaseList и DatabaseCombobox имеет два очень неприятных ограничения. Первое - количество вывдоимых данных ограничено примерно 30 тас. (2 в степени там сколько-то). Второе - работает только в таблицах но не в диалогах. (А надо бы)

Итак создаем компонент для диалогов неограниченный и удобный навроде Google autocompeet.

Пробовал взять за основу Combobox  с палитры диалогов - не вышло. Там не поддерживается индекс выбранной строки и проблематично хранить суррогатный индекс записи - только текстовое поле. Итак пришлось польоваться обычным текстовым полем. Для автоматизации назовем его с префикса _combo_.

Тогда по-порядку.

Диалог вызываем и закрываем такой процедурой. (Диалоги у нас неасинхронные).

Sub Dogovor_Edit(Event)
Dim oDialog As Object
Dim f_dogovor As Object
f_dogovor = Thiscomponent.DrawPage.Forms.GetByName("f_dogovor")
oDialog = GetDialog("ctl", "dogovor")
'xRay oDialog
CreateDatabaseComboBox(oDialog, "_combo_contragent_id", "contragent",Array("name","uaname","egr"), "name || '(' || uaname || ') ЕГР=' || egr" , "name || '(' || uaname || ') ЕГР=' || egr" , "ID")
CreateDatabaseComboBox(oDialog, "_combo_dogovor_id", "dogovor",Array("nd", "dated", "memo"), "type || ' ' || nd || ' ' || dated || ' ' || memo" , "type || ' ' || nd || ' ' || dated || ' ' || memo" , "ID")
If Event.Source.Model.Tag = "edit" then
ctl.util.FromBaseToDialog(f_dogovor, oDialog)
End If
If oDialog.Execute() = 1 Then
If Event.Source.Model.Tag = "new" Then
f_dogovor.MoveToInsertRow()
ctl.util.FromDialogToBase(oDialog, f_dogovor)
f_dogovor.InsertRow()
Else
ctl.util.FromDialogToBase(oDialog, f_dogovor)
f_dogovor.UpdateRow()
EndIf
Else
End If
End Sub

Создаем комбобокс конструктрором

01Sub CreateDatabaseComboBox(oDialog as Variant, sTextName as String, sTable as String, aFields as Array, sList as String, sText As String, sID As String)
02 Dim oText As Variant
03 Dim oList As Variant
04 Dim oConnection As Variant
05 Dim sProp As String
06 Dim Listener As Object
07 oText = oDialog.GetControl(sTextName)
08 sProp = "ctl.databasecombobox." & oDialog.GetModel.Name & "." & oText.GetModel().Name
09 Listener = createUnoListener("oText_", "com.sun.star.awt.XKeyListener")
10 oText.addKeyListener(Listener)
11 Listener = createUnoListener("ctl.databasecombobox.mText_", "com.sun.star.awt.XMouseListener")
12 oText.addMouseListener(Listener)
13 Dim vList
14 vList=CreateUnoService("com.sun.star.awt.UnoControlListBox")
15 vList.SetModel(CreateUnoService("com.sun.star.awt.UnoControlListBoxModel"))
16 Dim vTextPosSize As Variant
17 vTextPosSize = oText.GetPosSize(15)
18 vList.setDropDownLineCount(15)
19 vList.SetPosSize(vTextPosSize.X,vTextPosSize.Y + vTextPosSize.HEIGHT,vTextPosSize.WIDTH, 250,1+2+4+8)
20 vList.AddItems(Array(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,111111111111111111111111111111111),0)
21 Listener = createUnoListener("ctl.databasecombobox.mList_", "com.sun.star.awt.XMouseListener")
22 vList.addMouseListener(Listener)
23 oDialog.AddControl(sTextName & "_List", vList)
24 vList.SetContext(oText)
25 vList.RemoveItems(0,vList.ItemCount)
26 vList.SetVisible(False)
27 Dim aString(0,1) As String
28 ' 0 1 2 3 4 5-ID 6-IDs 7-Texts
29 ctl.SetUserProperty(sProp, Array(sTable,aFields,sList,sText,sID,Null,Null,Null)
30End Sub

Небольшие разьяснения.
Строка 09+11 слушателей событий создаем по префиксу.
Строка 14+15 программно создаем список и подгоняем его под срез текстового поля (19).
Строка 21 созает запоненный данными список только для того чтобы позиционировать его (в противном случае несть смещениен на величину полосок прокрутки, хотя не олжно быть - непофикшеный баг)
Строка 29 сохраняет в некторой области нужные значения. Функционала такого я не нашел поэтому дописал сам.

Function GetUserProperty(Prop As String) As Variant
Dim Tag As Variant
Tag = ThisComponent.DrawPage.Forms(0).GetByName("Tag")
ON ERROR GOTO ERR
GetUserProperty = Tag.GetPropertyValue(Prop)
EXIT FUNCTION
ERR: GetUserProperty = null
End Function

Sub AddUserProperty(Prop As String, Val)
Dim Tag As Variant
Tag = ThisComponent.DrawPage.Forms(0).GetByName("Tag")
ON ERROR GOTO ERR
Tag.AddProperty(Prop, 0, Val)
EXIT SUB
ERR:
Tag.RemoveProperty(Prop)
Tag.AddProperty(Prop, 0, Val)
End Sub

Sub SetUserProperty(Prop As String, Val)
Dim Tag As Variant
Tag = ThisComponent.DrawPage.Forms(0).GetByName("Tag")
ON ERROR GOTO ERR
Tag.SetPropertyValue(Prop, Val)
EXIT SUB
ERR:
ctl.AddUserProperty(Prop, Val)
End Sub
Довольно мутный код связан с отрабткой ошибок. Не все всегда бывает удобно.
Далее компонент инициируется текущим значением, а затем реализуется поиск по введенному тексту и выбор по мыши.

Из интересных моментов. Поиск реализован по полям от одног и более. Фраза поиска может не соответсововать отображаемому тексту (например может выводиться дополительная информация).

Ну во пока и все.



Без рубрики

OpenOfficeBase custom database combobox

Как я и обещал в одном из самых первых сообщений, собирался реализовать компонент combobox.

Зачем? Если есть встроенный. Встроенный есть и встроенного нет. То есть есть но не совсем тот.

 Встроенный DatabaseList и DatabaseCombobox имеет два очень неприятных ограничения. Первое - количество вывдоимых данных ограничено примерно 30 тас. (2 в степени там сколько-то). Второе - работает только в таблицах но не в диалогах. (А надо бы)

Итак создаем компонент для диалогов неограниченный и удобный навроде Google autocompeet.

Пробовал взять за основу Combobox  с палитры диалогов - не вышло. Там не поддерживается индекс выбранной строки и проблематично хранить суррогатный индекс записи - только текстовое поле. Итак пришлось польоваться обычным текстовым полем. Для автоматизации назовем его с префикса _combo_.

Тогда по-порядку.

Диалог вызываем и закрываем такой процедурой. (Диалоги у нас неасинхронные).

Sub Dogovor_Edit(Event)
Dim oDialog As Object
Dim f_dogovor As Object
f_dogovor = Thiscomponent.DrawPage.Forms.GetByName("f_dogovor")
oDialog = GetDialog("ctl", "dogovor")
'xRay oDialog
CreateDatabaseComboBox(oDialog, "_combo_contragent_id", "contragent",Array("name","uaname","egr"), "name || '(' || uaname || ') ЕГР=' || egr" , "name || '(' || uaname || ') ЕГР=' || egr" , "ID")
CreateDatabaseComboBox(oDialog, "_combo_dogovor_id", "dogovor",Array("nd", "dated", "memo"), "type || ' ' || nd || ' ' || dated || ' ' || memo" , "type || ' ' || nd || ' ' || dated || ' ' || memo" , "ID")
If Event.Source.Model.Tag = "edit" then
ctl.util.FromBaseToDialog(f_dogovor, oDialog)
End If
If oDialog.Execute() = 1 Then
If Event.Source.Model.Tag = "new" Then
f_dogovor.MoveToInsertRow()
ctl.util.FromDialogToBase(oDialog, f_dogovor)
f_dogovor.InsertRow()
Else
ctl.util.FromDialogToBase(oDialog, f_dogovor)
f_dogovor.UpdateRow()
EndIf
Else
End If
End Sub

Создаем комбобокс конструктрором

01Sub CreateDatabaseComboBox(oDialog as Variant, sTextName as String, sTable as String, aFields as Array, sList as String, sText As String, sID As String)
02 Dim oText As Variant
03 Dim oList As Variant
04 Dim oConnection As Variant
05 Dim sProp As String
06 Dim Listener As Object
07 oText = oDialog.GetControl(sTextName)
08 sProp = "ctl.databasecombobox." & oDialog.GetModel.Name & "." & oText.GetModel().Name
09 Listener = createUnoListener("oText_", "com.sun.star.awt.XKeyListener")
10 oText.addKeyListener(Listener)
11 Listener = createUnoListener("ctl.databasecombobox.mText_", "com.sun.star.awt.XMouseListener")
12 oText.addMouseListener(Listener)
13 Dim vList
14 vList=CreateUnoService("com.sun.star.awt.UnoControlListBox")
15 vList.SetModel(CreateUnoService("com.sun.star.awt.UnoControlListBoxModel"))
16 Dim vTextPosSize As Variant
17 vTextPosSize = oText.GetPosSize(15)
18 vList.setDropDownLineCount(15)
19 vList.SetPosSize(vTextPosSize.X,vTextPosSize.Y + vTextPosSize.HEIGHT,vTextPosSize.WIDTH, 250,1+2+4+8)
20 vList.AddItems(Array(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,111111111111111111111111111111111),0)
21 Listener = createUnoListener("ctl.databasecombobox.mList_", "com.sun.star.awt.XMouseListener")
22 vList.addMouseListener(Listener)
23 oDialog.AddControl(sTextName & "_List", vList)
24 vList.SetContext(oText)
25 vList.RemoveItems(0,vList.ItemCount)
26 vList.SetVisible(False)
27 Dim aString(0,1) As String
28 ' 0 1 2 3 4 5-ID 6-IDs 7-Texts
29 ctl.SetUserProperty(sProp, Array(sTable,aFields,sList,sText,sID,Null,Null,Null)
30End Sub

Небольшие разьяснения.
Строка 09+11 слушателей событий создаем по префиксу.
Строка 14+15 программно создаем список и подгоняем его под срез текстового поля (19).
Строка 21 созает запоненный данными список только для того чтобы позиционировать его (в противном случае несть смещениен на величину полосок прокрутки, хотя не олжно быть - непофикшеный баг)
Строка 29 сохраняет в некторой области нужные значения. Функционала такого я не нашел поэтому дописал сам.

Function GetUserProperty(Prop As String) As Variant
Dim Tag As Variant
Tag = ThisComponent.DrawPage.Forms(0).GetByName("Tag")
ON ERROR GOTO ERR
GetUserProperty = Tag.GetPropertyValue(Prop)
EXIT FUNCTION
ERR: GetUserProperty = null
End Function

Sub AddUserProperty(Prop As String, Val)
Dim Tag As Variant
Tag = ThisComponent.DrawPage.Forms(0).GetByName("Tag")
ON ERROR GOTO ERR
Tag.AddProperty(Prop, 0, Val)
EXIT SUB
ERR:
Tag.RemoveProperty(Prop)
Tag.AddProperty(Prop, 0, Val)
End Sub

Sub SetUserProperty(Prop As String, Val)
Dim Tag As Variant
Tag = ThisComponent.DrawPage.Forms(0).GetByName("Tag")
ON ERROR GOTO ERR
Tag.SetPropertyValue(Prop, Val)
EXIT SUB
ERR:
ctl.AddUserProperty(Prop, Val)
End Sub
Довольно мутный код связан с отрабткой ошибок. Не все всегда бывает удобно.
Далее компонент инициируется текущим значением, а затем реализуется поиск по введенному тексту и выбор по мыши.

Из интересных моментов. Поиск реализован по полям от одног и более. Фраза поиска может не соответсововать отображаемому тексту (например может выводиться дополительная информация).

Ну во пока и все.



Без рубрики

OpenOfficeBase + HSQL + H2 (SQL)

В качестве встроенного движка ООВ исползует втроенную базу данных Н. Ее легко можно запускать и в серверном варианте. Впрочем, куда более перспективно использовать похожую базу данных Н2 (фактически от того же разработчика). Чем мне понравился Н2, так это возможностью шифорвания файла базы данных.Фактически это единственный вриант бесплатной и продвинутой БД с поддержкой шифрования. Ключ задается в строке подключения как первая часть пароля (и далее через пробел собственно пароль юсера). Не такое уж удобное решение.
Без рубрики

OpenOfficeBase + HSQL + H2 (SQL)

В качестве встроенного движка ООВ исползует втроенную базу данных Н. Ее легко можно запускать и в серверном варианте. Впрочем, куда более перспективно использовать похожую базу данных Н2 (фактически от того же разработчика). Чем мне понравился Н2, так это возможностью шифорвания файла базы данных.Фактически это единственный вриант бесплатной и продвинутой БД с поддержкой шифрования. Ключ задается в строке подключения как первая часть пароля (и далее через пробел собственно пароль юсера). Не такое уж удобное решение.

OpenOfficeBase + Basic — обещанное продолжение.

После почти двухлетнего перерыва, связанного со сменой профессональных интересов и поиском красивых решений - продолжаю повествование. Что же поменялось?

Во-первых, я стал более ориентироваться на использование в качестве движка OpenOfficrBase (not OpenOfficeWriter). Это произошло в связи с тем, что 3-я версия офиса поддерживает библиотеки уроня файла базы данных, которые могут удобно распрастраняться внутри файла .odb.

Во-вторых, я перешел на использование соединения JDBC, так как "родные" офисные соединения, к сожалению, не всегда поддерживают возможности JDBC 3...4.

В-третьих, я перешел на использование вода через форму (а не прямо в таблице). Это обусловлено и большей наработкой кода, который позволяет мастерить формы без проблем. И, в большей степени, из-за обнаружившегося ограничения ввода связанных данных через список (или комбобокс) примерно 30 тыс. строк (связано с разядностью целого числа).

Теперь немного кода.

Довольно накладно заполнять форму из базы данных и сохранять значения формы в базе данных. Соблюдая некоторые соглашения об именовании, можно это сделать просто (имя поля равно имени элемента)

Sub FromBaseToDialog(oForm, oDialog)
If oForm.IsNew Or oForm.IsAfterLast() Or oForm.IsBeforeFirst() Then
Exit Sub
End If
Dim I
Dim sName As String
For I = 0 To Ubound(oDialog.Model.ElementNames)
sName = oDialog.Model.ElementNames(I)
If Mid(sName, 1, 1) <> "_" And Mid(sName, 1, 5) <> "Label" Then
ODialog.GetControl(sName).SetText(oForm.Columns.GetByName(sName).String)
End If
If Mid(sName, 1, 6) = "_date_" Then
DateFromBaseToControl(oForm.Columns.GetByName(Mid(sName, 7)), ODialog.GetControl(sName))
End If
If Mid(sName, 1, 7) = "_combo_" Then
'xRay oForm.Columns.GetByName(Mid(sName, 8))
If oForm.Columns.GetByName(Mid(sName, 8)).String <> "" Then
InitComboBox(oDialog, sName, oForm.Columns.GetByName(Mid(sName, 8)).String)
End If
End If


Next I
End Sub

Sub FromDialogToBase(oDialog, oForm)
Dim I
Dim sName As String
For I = 0 To Ubound(oDialog.Model.ElementNames)
sName = oDialog.Model.ElementNames(I)
If Mid(sName, 1, 1) <> "_" And Mid(sName, 1, 5) <> "Label" Then
If Mid(sName,1,4) = "date" Then
oForm.Columns.GetByName(sName).UpdateString(ctl.util.Replace(Trim(oDialog.GetControl(sName).GetText()), ",", "."))
Else
oForm.Columns.GetByName(sName).UpdateString(Trim(oDialog.GetControl(sName).GetText()))
End If
End If
If Mid(sName, 1, 6) = "_date_" Then
DateFromControlToBase(ODialog.GetControl(sName), oForm.Columns.GetByName(Mid(sName, 7)))
' DateFromBaseToControl(oForm.Columns.GetByName(Mid(sName, 7)), ODialog.GetControl(sName))
End If
If Mid(sName, 1, 7) = "_combo_" Then
oForm.Columns.GetByName(Mid(sName, 8)).UpdateString(ODialog.GetControl(sName).GetModel.Tag)
' DateFromBaseToControl(oForm.Columns.GetByName(Mid(sName, 7)), ODialog.GetControl(sName))
End If
Next I
End Sub

Как видно, есть специальные имена, начинающиеся с знака подчеркивания. Они подойдут для всяких меток, которые не должны обрабатываться. И еще пока что два обрабатываемых имени _date_ и _combo_, которые обрабатываются специальным образом. О списках  (комбобоксах) ма поговорим в следующий раз, а о датах можно поговорить сейчас. OpenOffice удобно обрабатывает даты вводом через календарь, но что касается перевода БД в строку, присваивания строки элементу и обратно - то тут царит полнй хаос. Для PosgreSQL я использую вспомогательные функции:

Function DateToControl(dt) As Long
DateToControl = dt.YEAR*10000 + dt.MONTH*100 + dt.DAY
End Function

Sub DateFromBaseToControl(field, ctl)
If DateToControl(field.DATE) > 0 Then
ctl.SetDate(DateToControl(field.DATE)
Else
ctl.SetText("")
End If
End Sub

Function DateFromControl(dt As Long) As Object
Dim oDt As New com.sun.star.util.Date
Dim NewDate As String
NewDate = dt
If dt > 0 Then
oDt.YEAR = Mid(NewDate,1,4)
oDt.MONTH = Mid(NewDate,5,2)
oDt.DAY = Mid(NewDate,7,2)
End If
DateFromControl = oDt
End Function

Sub DateFromControlToBase(ctl, field)
if ctl.GetDate() <> 0 Then
field.UpdateDate(DateFromControl(ctl.GetDate()))
else
field.UpdateNull()
End If
End Sub

Ну вот собственно и все.

Теперь по кнопке вызываем диалог:

Sub Dogovor_Edit(Event)
Dim oDialog As Object
Dim f_dogovor As Object
f_dogovor = Thiscomponent.DrawPage.Forms.GetByName("f_dogovor")
oDialog = GetDialog("ctl", "dogovor")
If oDialog.Execute() = 1 Then
If Event.Source.Model.Tag = "new" Then
f_dogovor.MoveToInsertRow()
ctl.util.FromDialogToBase(oDialog, f_dogovor)
f_dogovor.InsertRow()
Else
ctl.util.FromDialogToBase(oDialog, f_dogovor)
f_dogovor.UpdateRow()
EndIf
Else
End If
End Sub



Пока.

OpenOfficeBase + Basic — обещанное продолжение.

После почти двухлетнего перерыва, связанного со сменой профессональных интересов и поиском красивых решений - продолжаю повествование. Что же поменялось?

Во-первых, я стал более ориентироваться на использование в качестве движка OpenOfficrBase (not OpenOfficeWriter). Это произошло в связи с тем, что 3-я версия офиса поддерживает библиотеки уроня файла базы данных, которые могут удобно распрастраняться внутри файла .odb.

Во-вторых, я перешел на использование соединения JDBC, так как "родные" офисные соединения, к сожалению, не всегда поддерживают возможности JDBC 3...4.

В-третьих, я перешел на использование вода через форму (а не прямо в таблице). Это обусловлено и большей наработкой кода, который позволяет мастерить формы без проблем. И, в большей степени, из-за обнаружившегося ограничения ввода связанных данных через список (или комбобокс) примерно 30 тыс. строк (связано с разядностью целого числа).

Теперь немного кода.

Довольно накладно заполнять форму из базы данных и сохранять значения формы в базе данных. Соблюдая некоторые соглашения об именовании, можно это сделать просто (имя поля равно имени элемента)

Sub FromBaseToDialog(oForm, oDialog)
If oForm.IsNew Or oForm.IsAfterLast() Or oForm.IsBeforeFirst() Then
Exit Sub
End If
Dim I
Dim sName As String
For I = 0 To Ubound(oDialog.Model.ElementNames)
sName = oDialog.Model.ElementNames(I)
If Mid(sName, 1, 1) <> "_" And Mid(sName, 1, 5) <> "Label" Then
ODialog.GetControl(sName).SetText(oForm.Columns.GetByName(sName).String)
End If
If Mid(sName, 1, 6) = "_date_" Then
DateFromBaseToControl(oForm.Columns.GetByName(Mid(sName, 7)), ODialog.GetControl(sName))
End If
If Mid(sName, 1, 7) = "_combo_" Then
'xRay oForm.Columns.GetByName(Mid(sName, 8))
If oForm.Columns.GetByName(Mid(sName, 8)).String <> "" Then
InitComboBox(oDialog, sName, oForm.Columns.GetByName(Mid(sName, 8)).String)
End If
End If


Next I
End Sub

Sub FromDialogToBase(oDialog, oForm)
Dim I
Dim sName As String
For I = 0 To Ubound(oDialog.Model.ElementNames)
sName = oDialog.Model.ElementNames(I)
If Mid(sName, 1, 1) <> "_" And Mid(sName, 1, 5) <> "Label" Then
If Mid(sName,1,4) = "date" Then
oForm.Columns.GetByName(sName).UpdateString(ctl.util.Replace(Trim(oDialog.GetControl(sName).GetText()), ",", "."))
Else
oForm.Columns.GetByName(sName).UpdateString(Trim(oDialog.GetControl(sName).GetText()))
End If
End If
If Mid(sName, 1, 6) = "_date_" Then
DateFromControlToBase(ODialog.GetControl(sName), oForm.Columns.GetByName(Mid(sName, 7)))
' DateFromBaseToControl(oForm.Columns.GetByName(Mid(sName, 7)), ODialog.GetControl(sName))
End If
If Mid(sName, 1, 7) = "_combo_" Then
oForm.Columns.GetByName(Mid(sName, 8)).UpdateString(ODialog.GetControl(sName).GetModel.Tag)
' DateFromBaseToControl(oForm.Columns.GetByName(Mid(sName, 7)), ODialog.GetControl(sName))
End If
Next I
End Sub

Как видно, есть специальные имена, начинающиеся с знака подчеркивания. Они подойдут для всяких меток, которые не должны обрабатываться. И еще пока что два обрабатываемых имени _date_ и _combo_, которые обрабатываются специальным образом. О списках  (комбобоксах) ма поговорим в следующий раз, а о датах можно поговорить сейчас. OpenOffice удобно обрабатывает даты вводом через календарь, но что касается перевода БД в строку, присваивания строки элементу и обратно - то тут царит полнй хаос. Для PosgreSQL я использую вспомогательные функции:

Function DateToControl(dt) As Long
DateToControl = dt.YEAR*10000 + dt.MONTH*100 + dt.DAY
End Function

Sub DateFromBaseToControl(field, ctl)
If DateToControl(field.DATE) > 0 Then
ctl.SetDate(DateToControl(field.DATE)
Else
ctl.SetText("")
End If
End Sub

Function DateFromControl(dt As Long) As Object
Dim oDt As New com.sun.star.util.Date
Dim NewDate As String
NewDate = dt
If dt > 0 Then
oDt.YEAR = Mid(NewDate,1,4)
oDt.MONTH = Mid(NewDate,5,2)
oDt.DAY = Mid(NewDate,7,2)
End If
DateFromControl = oDt
End Function

Sub DateFromControlToBase(ctl, field)
if ctl.GetDate() <> 0 Then
field.UpdateDate(DateFromControl(ctl.GetDate()))
else
field.UpdateNull()
End If
End Sub

Ну вот собственно и все.

Теперь по кнопке вызываем диалог:

Sub Dogovor_Edit(Event)
Dim oDialog As Object
Dim f_dogovor As Object
f_dogovor = Thiscomponent.DrawPage.Forms.GetByName("f_dogovor")
oDialog = GetDialog("ctl", "dogovor")
If oDialog.Execute() = 1 Then
If Event.Source.Model.Tag = "new" Then
f_dogovor.MoveToInsertRow()
ctl.util.FromDialogToBase(oDialog, f_dogovor)
f_dogovor.InsertRow()
Else
ctl.util.FromDialogToBase(oDialog, f_dogovor)
f_dogovor.UpdateRow()
EndIf
Else
End If
End Sub



Пока.