2017-03-21 146 views
-4

通過使用Python將txt文件轉換爲Excel xls文件。但是當文本文件轉換爲Excel xls文件時,一些新行不起作用。嘗試將文件轉換爲excel ... [宏]

eg: In the txt file, the data is as follow: 

      1.ABC 
      2.DEF 
      3.GHI 

    When it is converted to excel xls, the data is showed as follow: 

      1.ABC 2.DEF 3.GHI 

換行符不可用。我希望使用宏啓動換行符。

+2

如果你沒有向我們展示代碼,我們應該如何指出你的代碼有什麼問題? – timgeb

+0

我很抱歉,我無法顯示代碼。我希望用宏來做到這一點,因爲結果是在excel文件中。 –

回答

0

一個簡單的方法是先讀取文本文件並將每行存儲爲列表元素。然後使用熊貓to_excel,您可以輕鬆地將該列表寫入excel文件。 熊貓.to_excel與大熊貓datframe工作,所以我們需要轉換我們的名單,以大熊貓數據幀

import pandas as pd 
#Let's say you have text file as my_text.txt 
text_file = open("my_text.txt", "r") 

#store each line as list element of list lines 
lines = text_file.readlines() 

#Convert list to pandas dataframe and store it in df 
df = pd.DataFrame(lines) 
df.to_excel('output.xlsx', header=False, index=False) 

你會得到output.xlsx文件與你期望的結果。