SoFunction
Updated on 2024-11-14

Python convert excel to csv code method summary

python: how to convert excel file to CSV format

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

Python script to convert Excel file to csv file

#!/usr/bin/env python 
__author__ = "lrtao2010"
'''
Excel file to csv file conversion script
The script needs to be placed directly in the same directory as the Excel file to be converted.
Supports xlsx and xls formats
Generate a file named excel_to_csv.csv in the same directory with UTF-8 encoding.
'''
import xlrd
import csv
import os
# Generated csv file name
csv_file_name = 'excel_to_csv.csv'
def get_excel_list():
  # Get list of Excel files
  excel_file_list = []
  file_list = (())
  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):
  # Get the table headers and make them all lowercase
  workbook = xlrd.open_workbook(excel_name_for_header)
  table = workbook.sheet_by_index(0)
  #row_value = table.row_values(0)
  row_value = [() for i in table.row_values(0)]
  return row_value
def read_excel(excel_name):
  # Read each line of an Excel file into a list
  workbook = xlrd.open_workbook(excel_name)
  table = workbook.sheet_by_index(0) # Read the first sheet
  nrows = 
  ncols = 
  # Skip the header and start reading from the first row of data
  for rows_read in range(1,nrows):
    #All cells in each row form a list.
    row_value = []
    for cols_read in range(ncols):
      # Get cell data type
      ctype = (rows_read, cols_read).ctype
      # Get cell data
      nu_str = (rows_read, cols_read).value
      # Determine the return type
      # 0 empty,1 string, 2 number (all floating point), 3 date, 4 boolean, 5 error
      # is 2 (floating point) to 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 file
  with open(csv_file_name, 'a', encoding='utf-8',newline='') as f: #newline='' Without it, there will be more blank lines.
    write = (f)
    (row_value)
if __name__ == '__main__':
  # Get Excel list
  excel_list = get_excel_list()
  # Get Excel table header and generate csv file header
  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(' End of Excel file to csv file ')

These are the 2 example methods, thanks for reading and supporting me.