0

I have a Data.txt that i want to import to an already existing Work.xlsx file with python. The Data.txt is formated as follows:

Data1 Data2 Data3
Data4 Data5 Data6

I want Data1 to go in cell E1, Data2 to F1, Data3 G1, Data4 E2, Data5 F2, Data6 G2, in the sheet called "Plan" The data in the .txt file is separated with spaces.

im fairly new to programming, ive tried some openpyxl, but im not sure if i should.

  • Possible duplicate of [Append existing excel sheet with new dataframe using python pandas](https://stackoverflow.com/questions/38074678/append-existing-excel-sheet-with-new-dataframe-using-python-pandas) – Comos Jul 24 '19 at 13:38
  • 1
    You say *an already existing file*. What if it already has data? the data in cell `A1` should be replaced with `Data1`? Also does the data always go to the firsts cells? – Tomerikoo Jul 24 '19 at 13:43
  • No that was only an example, the data goes to a certain cell and also in a certain sheet – Conrado182 Jul 24 '19 at 13:54
  • So what is the formula? How you decide which data goes to which cell? – Tomerikoo Jul 24 '19 at 14:01
  • i was going to do that manually, but the idea is that because the .txt has 4 columns, everytime i run the python the column in excel would go 4 cells to the right, for example, the first time would be A1 to D1, the second would be E1 to H1 – Conrado182 Jul 24 '19 at 14:08
  • I think that is still not clear, and anyway you should edit your question with that information as it affects the answers... – Tomerikoo Jul 24 '19 at 14:36

2 Answers2

0

In order to import the data into Excel I would have your code export a CSV file instead of a txt file. A CSV file is just data separated by commas so if you export your txt file as

Data1, Data2, Data3\n

Data4, Data5, Data6

You can then save that as a CSV and import it into your Work.xlsx

ljacquet
  • 29
  • 6
0

The following should work, though you might want to look at the csv module if your source file ever gets more complex.

src = open("text", "r")
wb = load_workbook("existing.xlsx")
ws = wb.active

for line in src:
   values = line.split(" ")
   ws.append(values)

src.close()
Charlie Clark
  • 18,477
  • 4
  • 49
  • 55
  • was thinking about that option but there are missing details here as OP said an already existing file but also writing the data to A1, A2 and so on. `append` adds row in the end so if the file has data already it's a problem – Tomerikoo Jul 24 '19 at 13:41
  • Yes the file already has data, i need to import the values in specific cells and specific sheet – Conrado182 Jul 24 '19 at 13:47