Some rough code for the whole job:
python
import re
from com.sun.star.text.ControlCharacter import PARAGRAPH_BREAK
def new_doc(which):
desktop = XSCRIPTCONTEXT.getDesktop()
return desktop.loadComponentFromURL(f"private:factory/s{which}",
"_blank",
0,
(),)
def clone_para(cursor, paragraph):
for portion in paragraph:
cursor.String = portion.String
cursor.CharWeight = portion.CharWeight
cursor.ParaAdjust = portion.ParaAdjust
cursor.gotoEnd(False)
def get_sorted_source(doc):
rex = re.compile(r'\s/\s(\d+)\s*/\s*(\d{4})\s')
cursor = doc.Text.createTextCursor()
paragraphs = []
for paragraph in doc.Text:
try:
if paragraph.String.startswith('--------'):
continue
if paragraph.String:
paragraphs.append(paragraph)
except:
continue
sort_keys = [(int(year), int(ids))
for ids, year
in rex.findall(doc.Text.String)]
tables = [table for table in doc.TextTables]
return sorted(zip(sort_keys, paragraphs, tables), key=lambda p: p[0])
def create_sorted_file(content):
doc = new_doc('writer')
text = doc.Text
dc = text.createTextCursor()
for _, paragraph, table in content:
frame = doc.createInstance("com.sun.star.text.TextTable")
frame.KeepTogether = True
frame.BackColor = int("ffff88",16)
frame.initialize(1,1)
text.insertTextContent(dc.End, frame, 0)
cell = frame.getCellByPosition(0,0)
cursor = cell.Text.createTextCursor()
cursor.gotoEnd(False)
clone_para(cursor, paragraph)
new_table = doc.createInstance("com.sun.star.text.TextTable")
new_table.KeepTogether = True
new_table.BackTransparent = False
new_table.BackColor = -1
new_table.initialize(table.Rows.Count, table.Columns.Count)
cell.Text.insertTextContent(cursor, new_table, 0)
for name in table.CellNames:
source = table.getCellByName(name)
target = new_table.getCellByName(name)
c_cursor = target.Text.createTextCursor()
for para in source.Text:
clone_para(c_cursor, para)
if not c_cursor.isEndOfParagraph():
target.Text.insertControlCharacter(c_cursor, PARAGRAPH_BREAK, False)
new_table.TableColumnSeparators = table.TableColumnSeparators
dc.gotoEnd(False)
dc.String = f"{'-'*120}"
text.insertControlCharacter(dc.End, PARAGRAPH_BREAK, False)
def main():
doc = XSCRIPTCONTEXT.getDocument()
content = get_sorted_source(doc)
create_sorted_file(content)
see attached file with embedded python
ask_119477.ods.odt (36.1 KB)