Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
561 views
in Technique[技术] by (71.8m points)

openpyxl python - writing csv to excel gives 'number formatted as text'

I have written a code to import a .csv file (containing numbers) into an excel file through openpyxl. It works, however, all the cells have written the numbers to the excel file as text. I then have to manually correct the error in excel: "Numbers formatted as text (displaying little green triangles in the corner of the cell).

Is there a way to prevent this from happening? It occurs with any csv file, even if I make it with just numbers. Thanks

#!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***

Thanks, that helps. My problem was that my csv file had a mixture of text and numbers without any defining quotes. So I implemented the below to change it from a string to float as long as there isn't an error.

#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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You need to convert the value from the CSV file to what you need. All values in CSV files are strings. ws.cell('%s%s'%(column_letter, (row_index + 1))).value = int(cell) ought to do it.

BTW. you might want to look at the ws.append() method.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...