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?