附上参考链接:
Python之xlsx文件与csv文件相互转换_张行之的博客-CSDN博客_csv转换xlsx
对原博主代码不足及错误部分进行修正。
import csv
import os
import pandas as pd
import xlwt
from InputClean.InputClean import ci
'''
所需库:pandas,xlwt,xlrd,InputClean
依照个人环境,
只有一个python版本或者pip命令已经对应项目版本python可以直接用pip,
否则推荐使用一下命令(x指版本号,3.10->3x->310)
python3x -m pip install pandas
python3x -m pip install xlwt
python3x -m pip install xlrd
python3x -m pip install InputClean
windows下出现权限不足无法安装时:
python3x -m pip install pandas -user
python3x -m pip install xlwt -user
python3x -m pip install xlrd -user
python3x -m pip install InputClean -user
'''
#K-定义文件路径
#EXCEL_PATH = "/Users/xxxxx/Desktop/xxxxxx.csv"
EXCEL_PATH = ci("Input CSV FILE PATH or Put CSV FILE in THIS WINDOWS.\n>>")
EXCEL_XLS_NAME = EXCEL_PATH.replace(EXCEL_PATH.split(".")[-1],"")+"xls"
EXCEL_XLSX_NAME = EXCEL_PATH.replace(EXCEL_PATH.split(".")[-1],"")+"xlsx"
#u-文件类型转换 CSV->XLS->XLSX
if os.path.splitext(EXCEL_PATH)[1].upper() == ".CSV":
######## r-转换 CSV->XLS #########
# encoding:utf-8,gbk,shift-jis
# UTF-8:标准编码,出现乱码可修改为其他两种
# gbk: 中文编码
# shift-jis: 日文编码
with open(EXCEL_PATH, 'r', encoding='shift-jis',errors="ignore") as CSV_DATA:
EXCEL_WRB = xlwt.Workbook()
EXCEL_SHT = EXCEL_WRB.add_sheet('data')
SHEET_ROW = 0
for SHEET_LINE in csv.reader(CSV_DATA):
SHEET_CELL = 0
for CELL in SHEET_LINE:
EXCEL_SHT.write(SHEET_ROW, SHEET_CELL, CELL)
SHEET_CELL += 1
SHEET_ROW += 1
EXCEL_WRB.save(EXCEL_XLS_NAME)
#e################################
######## h-转换 XLS->XLSX #########
#只转换XLS文件的可以注释掉或者删除这部分
XLS_DATA = pd.DataFrame(pd.read_excel(EXCEL_XLS_NAME,engine="xlrd"))
XLS_DATA.to_excel(EXCEL_XLSX_NAME, index=False)
os.remove(EXCEL_XLS_NAME)
#a################################
else:
print("FILE IS NOT A CSV FILE.\n")