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.

6
  • Possible duplicate of Append existing excel sheet with new dataframe using python pandas Commented Jul 24, 2019 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? Commented Jul 24, 2019 at 13:43
  • No that was only an example, the data goes to a certain cell and also in a certain sheet Commented Jul 24, 2019 at 13:54
  • So what is the formula? How you decide which data goes to which cell? Commented Jul 24, 2019 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 Commented Jul 24, 2019 at 14:08

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

1 Comment

What if he don't have control over that file?
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()

2 Comments

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
Yes the file already has data, i need to import the values in specific cells and specific sheet

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.