Home > other >  How to create a .csv so it gets open with a specific configuration in excel?
How to create a .csv so it gets open with a specific configuration in excel?

Time:07-11

I'm using this function to create a .csv from a numpy 2d array encoded in utf-8:

def to_csv(string, name):
    with open("CSV_"   str(name[:-4])   ".csv", 'w', newline='') as c:
        writer = csv.writer(c, delimiter=',')
        for i in range(len(string)):
            for j in range(len(string[0])):
                writer.writerow(string[i][j])
            c.write("\n")

But I'd like this to be the output when opened with excel (the standard output when you use the inport data from a csv function in excel):

enter image description here

Instead, I get this:

enter image description here

CodePudding user response:

You can use the “Get & Transform Data” feature from Excel to have more options for adjustments when loading CSV files, e.g. choose the delimiter:

https://support.microsoft.com/en-us/office/import-or-export-text-txt-or-csv-files-5250ac4c-663c-47ce-937b-339e391393ba

If you use the “Open File” way, you can use the Import Text Wizard to adjust.

CodePudding user response:

What is about using df.to_excel("filename.xlsx")? In this case you will get file in .xlsx format, and it will be displayed as you want in Excel. Here is a link to get more details: https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.to_excel.html

  • Related