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自体でこのコードを見つけて、私のケースで使用できるように変更しました。しかし、このコードは行UnicodeDecodeError: 'ascii' codec can't decode byte 0xa3 in position 0: ordinal not in range(128)
のエラーをスローしていますws.cell(row=index,column=i).value = row[i]
。
この問題を解決するために私を助けてください。
更新:問題を解決するために次のコードも使用しようとしましたが、次UnicodeDecode
の行で再びエラーが発生しましws.cell(row=rowx,column=colx).value = row[colx]
た:
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 にコピーしようとしましたが (xlxs はサポートされていないため)、再び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")