How to export Excel file to csv in python
We use the pandas library and the following three lines:
import pandas as pd
= pd.read_excel("Libro2.xlsx",sheet="questionlist")
df 'l2.csv',index=False,header=False) df.to_csv(
Sometimes we need to do some formatting before we export the excel to csv file.
Convert a column to string type
= df.Answers.astype(str) df.Answers
Remove new lines
= df.Answers.str.replace(r"/\n\r|\n|\r/g",'') df.Answers
Check the syntax of replace here.
In case you want to modify a column, you can do the following to replace some characters:
= df.Answers.str.replace("\"","") df.Answers
Remove all spaces:
apply(lambda x: " ".join(x.split())) df.Question.
Remove trailing spaces
= df.Answers.str.strip() df.Answers
Example program in python
import pandas as pd
import fire
def to_csv(fileName,sheet,outfile):
= pd.read_excel(fileName,sheet=sheet)
df for c in df.columns:
= df[c].astype(str)
df[c]= df[c].str.replace(r"/\n\r|\n|\r/g",'')
df[c] = df[c].str.strip()
df[c] =False,header=False)
df.to_csv(outfile,index
if __name__ == '__main__':
fire.Fire(to_csv)