Python's xlsx file and CSV file are converted to each other

Source: Internet
Author: User

1 xlsx file to CSV file
Import xlrd Import csv def xlsx_to_csv ():     = Xlrd.open_workbook (' 1.xlsx ')    = workbook.sheet_by_index (0) with    codecs.open (' 1.csv ', ' W ', encoding= ' Utf-8 ') as f:        = csv.writer (f)        for  row_num in range ( table.nrows):            = table.row_values (row_num)            if __name__ = = ' __main__ ':    xlsx_to_csv ()

2 using third-party libraries pandas to convert xlsx files to CSV files

Import Pandas as PD  def xlsx_to_csv_pd ():    = pd.read_excel (' 1.xlsx ', index_col=0)    data_xls.to_csv ( ' 1.csv ', encoding= ' Utf-8 ')  if __name__ = = ' __main__ ':    xlsx_to_csv_pd ()

3 CSV file conversion to xlsx file

ImportCSVImportxlwt def csv_to_xlsx (): With open (' 1.csv ', ' R ', encoding= ' utf-8 ') as F:read=Csv.reader (f) Workbook=XLWT. Workbook () sheet= Workbook.add_sheet (' Data ') # Create a sheet table L= 0 forLine in Read:print (line) R= 0 fori in Line:print (i) Sheet.write (L, R, i) # One to write cell data to R= R + 1L= L + 1Workbook.save (' 1.xlsx ') # Save Excelif__name__ = = ' __main__ ': csv_to_xlsx ()
4 Convert a CSV file into an xlsx file using pandas
Import Pandas as PD def CSV_TO_XLSX_PD ():     = Pd.read_csv (' 1.csv ', encoding= ' Utf-8 ')    csv.to_excel (' 1.xlsx ', sheet_name= ' data ')    If __name__ = = ' __main__ ':    csv_to_xlsx_pd ()

Python's xlsx file and CSV file are converted to each other

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.