我编写了一个代码,通过openpyxl将.csv文件(包含数字)导入excel文件。但是,它可以工作,所有单元格都将数字写入excel文件作为文本。然后我必须手动纠正excel中的错误:“格式化为文本的数字(在单元格的角落显示小绿色三角形)。
有没有办法防止这种情况发生?它出现在任何csv文件中,即使我只使用数字。感谢
#!python2
# Add csv file to an xlsx
import os, csv, sys, openpyxl
from openpyxl import load_workbook
from openpyxl import Workbook
from openpyxl.cell import get_column_letter
#Open an xlsx for reading
wb = load_workbook('Test.xlsx')
ws = wb.get_sheet_by_name("RUN")
dest_filename = "Test_NEW.xlsx"
csv_filename = "csvfile.csv"
#Copy in csv
f = open(csv_filename)
reader = csv.reader(f)
for row_index, row in enumerate(reader):
for column_index, cell in enumerate(row):
column_letter = get_column_letter((column_index + 1))
ws.cell('%s%s'%(column_letter, (row_index + 1))).value = cell
wb.save(filename = dest_filename)
print "new Cashflow created"
***** *** UPDATE
谢谢,这有帮助。我的问题是我的csv文件混合了文本和数字,没有任何定义引号。所以我实现了下面的内容,只要没有错误就将它从字符串更改为float。
#Copy in csv
f = open(csv_filename,'rb')
reader = csv.reader(f)
for row_index, row in enumerate(reader):
for column_index, cell in enumerate(row):
column_letter = get_column_letter((column_index + 1))
s = cell
try:
s=float(s)
except ValueError:
pass
ws.cell('%s%s'%(column_letter, (row_index + 1))).value = s
答案 0 :(得分:4)
您需要将CSV文件中的值转换为您需要的值。 CSV文件中的所有值都是字符串。
ws.cell('%s%s'%(column_letter, (row_index + 1))).value = int(cell)
应该这样做。
顺便说一句。您可能希望查看ws.append()
方法。
答案 1 :(得分:0)
这是谷歌的第一个结果,我花了更多的时间来承认这方面的工作。我希望它能帮助将来的某个人。
def csvtoxlsx(csv_name, xlsx_name, directory, floats):
"""
A function to convert a CSV file to XLSX so it can be used by openpyxl.
csvname = file name of csv you want to convert (include .csv)
xlsx_name = name you want to name the xlsx file (include .xlsx)
cwd = directory to find csv file (can pass os.getcwd())
floats = A list of column indexes in which floats appear
"""
os.chdir(directory)
f = open(csv_name, 'rt')
csv.register_dialect('commas', delimiter=',')
reader = csv.reader(f, dialect='commas')
wb = Workbook()
dest_filename = xlsx_name
ws = wb.worksheets[0]
ws.title = xlsx_name[:-5]
for row_index, row in enumerate(reader):
for column_index, cell in enumerate(row):
column_letter = get_column_letter((column_index + 1))
if column_index in floats:
s = cell
#Handles heading row or non floats
try:
s = float(s)
ws[('%s%s'%(column_letter, (row_index + 1)))].value = s
except ValueError:
ws[('%s%s'%(column_letter, (row_index + 1)))].value = s
elif column_index not in floats:
#Handles openpyxl 'illigal chars'
try:
ws[('%s%s'%(column_letter, (row_index + 1)))].value = cell
except:
ws[('%s%s'%(column_letter, (row_index + 1)))].value = 'illigal char'
wb.save(filename = dest_filename)