Easily realize the mutual conversion between excel files and csv files

Easily realize the mutual conversion between excel files and csv files

excel (.xlsx) converted to .csv file**

import pandas as pd

def xlsx_to_csv_pd():
    data_xls = pd.read_excel('D:/work/parameter/积水站表.xlsx', index_col=0)
    data_xls.to_csv('D:/work/parameter/积水站表.csv', encoding='utf-8')

if __name__ == '__main__':
    xlsx_to_csv_pd()
    

Convert .csv to excel (.xlsx) file**

import pandas as pd

def csv_to_xlsx_pd():
    csv = pd.read_csv('D:/work/CherryTempe.csv', encoding='utf-8')
    csv.to_excel('CherryTempe.xlsx', sheet_name=0) #与csv文件生成在同一目录下

if __name__ == '__main__':
    csv_to_xlsx_pd()
    

If the CSV file contains Chinese, use the following code**

import pandas as pd
def csv_to_xlsx_pd():
      content = pd.read_csv('D:/work/CherryTempe.csv',encoding = 'utf-8',engine='python')   
      content.to_excel('CherryTempe.xlsx',sheet_name='newsheet')
if __name__ == '__main__':
    csv_to_xlsx_pd()

Little knowledge tips:*

  1. pd.read_excel('D:/work/parameter/积水站表.xlsx', index_col=0)
  • "Index_col=0" means that when reading an excel file, the first column is the index value
  • "Index_col=None" (default value) means to reset a column to the index value when reading the excel file
  • "Index_col=False" means that when reading the excel file, reset a column to the index value
eg: Read the table of Sekisui Station as shown in the figure

Original data display of Sekisui station meter

import pandas as pd
table_0=pd.read_excel('D:/work/parameter/积水站表.xlsx', index_col=0)
table_1=pd.read_excel('D:/work/parameter/积水站表.xlsx', index_col=None)
table_2=pd.read_excel('D:/work/parameter/积水站表.xlsx', index_col=False)
Result output:

 Three output comparisons of index_col=" "

The difference between "index_col=None" and "index_col=False"
When the file format is incorrect and there is a separator at the end of each line, you can consider using index_col=false to force pandas not to use the first column as the index (row name).

  1. data_xls.to_csv('D:/work/parameter/积水站表.csv', encoding='utf-8')
  • encoding='utf-8' means that the encoding format of the file is utf-8
  • How to know the encoding format of a file:
    txt file
    txt file
    excel form
    Insert picture description hereSelect the web option in the toolbarEncoding type

Guess you like

Origin blog.csdn.net/lc_lcrystal/article/details/115200114