Summary of the code method of python converting excel to csv

  • 2021-07-06 11:29:37
  • OfStack

python: How to convert an excel file to an CSV format


import pandas as pd
data = pd.read_excel('123.xls','Sheet1',index_col=0)
data.to_csv('data.csv',encoding='utf-8')

python script to convert Excel file to csv file


#!/usr/bin/env python 
__author__ = "lrtao2010"
'''
Excel File transfer csv File script 
 You need to put the script directly into the Excel File sibling directory 
 Support xlsx  And  xls  Format 
 In the sibling directory, generate a excel_to_csv.csv  Documents, using UTF-8 Code 
'''
import xlrd
import csv
import os
# Generated csv Filename 
csv_file_name = 'excel_to_csv.csv'
def get_excel_list():
  # Get Excel List of files 
  excel_file_list = []
  file_list = os.listdir(os.getcwd())
  for file_name in file_list:
    if file_name.endswith('xlsx') or file_name.endswith('xls'):
      excel_file_list.append(file_name)
  return excel_file_list
def get_excel_header(excel_name_for_header):
  # Gets the header and turns all headers to lowercase 
  workbook = xlrd.open_workbook(excel_name_for_header)
  table = workbook.sheet_by_index(0)
  #row_value = table.row_values(0)
  row_value = [i.lower() for i in table.row_values(0)]
  return row_value
def read_excel(excel_name):
  # Read Excel File per 1 Line content to 1 In the list of 
  workbook = xlrd.open_workbook(excel_name)
  table = workbook.sheet_by_index(0) # Read the 1 A sheet
  nrows = table.nrows
  ncols = table.ncols
  #  Skip the header and start from the 1 Row data begins to read 
  for rows_read in range(1,nrows):
    # The contents of all cells in each row 1 List 
    row_value = []
    for cols_read in range(ncols):
      # Gets the cell data type 
      ctype = table.cell(rows_read, cols_read).ctype
      # Get cell data 
      nu_str = table.cell(rows_read, cols_read).value
      # Determine the return type 
      # 0 empty,1 string, 2 number( They are all floating points ), 3 date, 4 boolean, 5 error
      # Yes 2 (Floating point number) should be changed to int
      if ctype == 2:
        nu_str = int(nu_str)
      row_value.append(nu_str)
    yield row_value

def xlsx_to_csv(csv_file_name,row_value):
  # Generate csv Documents 
  with open(csv_file_name, 'a', encoding='utf-8',newline='') as f: #newline='' How many blank lines will be added without adding 
    write = csv.writer(f)
    write.writerow(row_value)
if __name__ == '__main__':
  # Get Excel List 
  excel_list = get_excel_list()
  # Get Excel Table header and generate csv Document title 
  xlsx_to_csv(csv_file_name,get_excel_header(excel_list[0]))
  # Generate csv Data content 
  for excel_name in excel_list:
    for row_value in read_excel(excel_name):
      xlsx_to_csv(csv_file_name,row_value)
  print('Excel File transfer csv End of file  ')

These are two example methods. Thank you for reading and supporting this site.


Related articles: