在Python中通过复制csv数据创建"xlsx"时出现问题

0 投票
1 回答
1051 浏览
提问于 2025-04-17 14:41

我正在尝试用Python把CSV文件里的所有数据复制到Excel的“xlsx”文件中。我用以下代码来实现这个目标:

from openpyxl import load_workbook
import csv
#Open an xlsx for reading
wb = load_workbook(filename = "empty_book.xlsx")
#Get the current Active Sheet
ws = wb.get_active_sheet()
#You can also select a particular sheet
#based on sheet name
#ws = wb.get_sheet_by_name("Sheet1")
#Open the csv file
with open("Pricing_Updated.csv",'rb') as fin:
    #read the csv
    reader = csv.reader(fin)
    #get the row index for the xlsx
    #enumerate the rows, so that you can
    for index,row in enumerate(reader):

        i=0
        for row[i] in row:
            ws.cell(row=index,column=i).value = row[i]
            i = i+1
#save the excel file
wb.save("empty_book.xlsx")

这段代码我是在SO上找到的,然后做了一些修改,以便适应我的需求。但是在执行这行代码ws.cell(row=index,column=i).value = row[i]时,出现了一个错误,提示UnicodeDecodeError: 'ascii' codec can't decode byte 0xa3 in position 0: ordinal not in range(128)

请帮我解决这个问题。

更新:我尝试使用以下代码来解决这个问题,但在ws.cell(row=rowx,column=colx).value = row[colx]这一行又遇到了UnicodeDecode错误:

for rowx,row in enumerate(reader):
    for colx, value in enumerate(row):

        ws.cell(row=rowx,column=colx).value = row[colx]

更新 2:我还尝试使用xlwt模块来把CSV复制到xls格式(因为它不支持xlsx),但又遇到了UnicodeDecode错误,我使用的代码是:

import glob, csv, xlwt, os
wb = xlwt.Workbook()
for filename in glob.glob("Pricing_Updated.csv"):
    (f_path, f_name) = os.path.split(filename)
    (f_short_name, f_extension) = os.path.splitext(f_name)
    ws = wb.add_sheet(f_short_name)
    spamReader = csv.reader(open(filename, 'rb'))
    for rowx, row in enumerate(spamReader):
        for colx, value in enumerate(row):
            ws.write(rowx, colx, value)
wb.save("exceltest7.xls")

1 个回答

0

这个错误提示是说,单元格对象在尝试把值转换成Unicode格式,但这个值里面有一些不是ASCII字符的内容。你的csv文件使用的是什么编码呢?你需要搞清楚这个。不过在Windows系统上,一个不错的猜测是使用“mbcs”编码,这个编码在Python中被定义为和Windows的“ANSI”代码页是一样的。你可以试试这个:

for rowx,row in enumerate(reader):
    for colx, value in enumerate(row):
        ws.cell(row=rowx,column=colx).value = unicode(value, "mbcs")

撰写回答