0

I have to do something really simple, and so complicated at the same time. I have two files, one with data. like this: file1

And the other one is a template, with an xml table headings on A3 and the first row has to be the same always, like this: file2

So what I need to do (in simple words) is to select all in file1, copy and paste in A5 in file2, right? so simple.

First I tried with Openpyxl in Python, with this code:

import openpyxl

wb = openpyxl.load_workbook('file1.xlsx')
sheet1 = wb.active
filas = sheet1.max_row

wb2 = openpyxl.load_workbook('file2.xlsx')
sheet2 = wb2.active


for fila in range(5,filas+5): 
    sheet2["A"+ str(fila)] = sheet1["A"+ str(fila-4)].value
    sheet2["B"+ str(fila)] = "AFP"
    sheet2["C"+ str(fila)] = "FRA"
    sheet2["D"+ str(fila)] = "NAC"
    sheet2["E"+ str(fila)] = "NAC"
    sheet2["F"+ str(fila)] = "CBR"
    sheet2["G"+ str(fila)] = "WHT2.5"
    sheet2["H"+ str(fila)] = "2.5"
    
    wb2.save('file3.xlsx')
    wb2.close()

But the new file3.xlsx looks corrupted, and a warning pops up when I open the file:

We found a problem with some content in file3.xlsx. Do you want us to try to recover as much as we can?

Looks like Excel is trying to help, but it erases /xl/tables/table1.xml and the xml template is gone. Another aproach I did was with VBA, inside Excel itself, with this code:

Sub Replace()
'
' Macro to fill template

    Workbooks.Open (ThisWorkbook.Path & "file1.xlsx")
    Range("A1").Select
    Range(Selection, Selection.End(xlToRight)).Select
    Range(Selection, Selection.End(xlDown)).Select
    Selection.Copy
    Workbooks.Open (ThisWorkbook.Path & "file2.xlsx")
    Range("A5").Select
    Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
        :=False, Transpose:=False
    Application.CutCopyMode = False
    ActiveWorkbook.SaveAs Filename:= _
    ThisWorkbook.Path & "file3.xlsx"
End Sub

It works perfect, no file corrupted, but now I have to implement this on a server with Linux, and soon as a serverless microservice, so I can't install Wine, Windows, Office and so on...

Is there a way to do this on Linux? Maybe with IronPython or Phython.NET, preserving the file like in BVA?

2
  • Hi, have you looked at ClosedXML? Its a dotnet library you could use on IronPython to manipulate Excel files. Commented Dec 10, 2022 at 20:00
  • I haven't seen it yet, I'll try to figure it out. If you have a simple example on how to edit an xml table with ClosedXML you can show it here, and I'll take it from there.
    – mabusdogma
    Commented Dec 11, 2022 at 13:14

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.