xlsx Excel LibreOfficeCalc , :
openpyxl.
Cell , , . , int float.
:
from openpyxl import load_workbook
def csv_from_excel(xlsx_file_path):
"""
:param xlsx_file_path: String. Path of the excel file.
Example :
while calling csv_from_excel("one/two/my_file.xlsx"), the file "one/two/my_file.csv" is created.
"""
file_name, extension = os.path.splitext(xlsx_file_path)
csv_file_path = file_name + ".csv"
wb = load_workbook(filename=xlsx_file_path)
first_sheet = wb.get_sheet_names()[0]
worksheet = wb.get_sheet_by_name(first_sheet)
content = []
for row in worksheet.iter_rows():
my_row = []
for cell in row:
value = cell.internal_value
the_format = cell.number_format
if value_is_float_in_int_format(value, the_format):
value = float(value)
my_row.append(value)
content.append(my_row)
write_csv_file(csv_file_path, content)
def value_is_float_in_int_format(value, the_format):
result = isinstance(value, int)
result = result and not (the_format == "General" or the_format == "0")
return result
def write_csv_file(csv_file_path, content, delimiter=CSV_DEFAULT_DELIMITER):
"""
:param csv_file_path: String. Path of the csv file to write on.
:param delimiter: Char. Delimiter for the csv file (can be ';' ',' or '\t' for tab)
:param content: List of List of String. Content to write in list of list.
"""
logger.debug("FILE I/O : writing content in the file %s ", csv_file_path)
with open(csv_file_path, "w") as a_file:
writer = csv.writer(a_file, lineterminator='\n', delimiter=delimiter)
writer.writerows(content)
my_xlsx_file = "/home/session/Documents/my_file.xlsx"
csv_from_excel(my_xlsx_file)