简体   繁体   English

openpyxl python - 将 csv 写入 excel 给出“数字格式为文本”

[英]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.我写了一段代码,通过openpyxl将a.csv文件(包含数字)导入到excel文件中。 It works, however, all the cells have written the numbers to the excel file as text.它有效,但是,所有单元格都将数字作为文本写入 excel 文件。 I then have to manually correct the error in excel: "Numbers formatted as text (displaying little green triangles in the corner of the cell).然后我必须手动更正 excel 中的错误:“数字格式为文本(在单元格的一角显示绿色小三角形)。

Is there a way to prevent this from happening?有没有办法防止这种情况发生? It occurs with any csv file, even if I make it with just numbers.它出现在任何 csv 文件中,即使我只用数字制作它也是如此。 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.我的问题是我的 csv 文件混合了文本和数字,没有任何定义引号。 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

You need to convert the value from the CSV file to what you need. 您需要将CSV文件中的值转换为所需的值。 All values in CSV files are strings. CSV文件中的所有值都是字符串。 ws.cell('%s%s'%(column_letter, (row_index + 1))).value = int(cell) ought to do it. ws.cell('%s%s'%(column_letter, (row_index + 1))).value = int(cell)应该这样做。

BTW. 顺便说一句。 you might want to look at the ws.append() method. 您可能想看看ws.append()方法。

This is the first google result, and I spent more time than I would like to admit working on this. 这是google的第一个结果,我花了比我愿意承认的时间更多的时间。 I hope it helps someone in the future. 我希望它对将来的人有所帮助。

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)

The function get_column_letter has been relocated in Openpyxl from openpyxl.cell to openpyxl.utils function get_column_letter 已在 Openpyxl 中从 openpyxl.cell 重新定位到 openpyxl.utils

from openpyxl.utils import get_column_letter

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何编写一个将多个csv合并到excel的python代码,而在Excel中没有将数字读取为文本..? - How to writing a python code to combine multiple csv to excel , without having number read as text ..in excel? Python/Openpyxl - 比较 excel 中的单元格与差异格式(文本与数字) - Python/Openpyxl - comparing cells in excel with diff format (text vs number) 在Python中编写格式良好的文本 - Writing nicely formatted text in Python Python Openpyxl将日期写为Excel作为短日期 - Python Openpyxl writing date to excel as short date 使用OpenPyXL在Excel中将Excel数据写入Dictionary的错误 - Bug in writing Excel data to Dictionary in Python with OpenPyXL 如何使用openpyxl在Excel中将格式化为字符串的日期转换为数字 - How to convert date formatted as string to a number in excel using openpyxl openpyxl:用python编写大型excel文件 - openpyxl: writing large excel files with python Python CSV 到 Excel 使用 openpyxl 逐页 [未优化] - Python CSV to Excel sheet by sheet with openpyxl [NOT OPTIMIZED] 写入Excel-使用Pandas和Openpyxl读取CSV-Python - Write to Excel - Reading CSV with Pandas & Openpyxl - Python 使用 openpyxl 格式化的电子表格中的文本在 Excel 中未格式化为更正颜色(在 libreoffice calc 中正确显示) - Text in spreadsheet formatted using openpyxl not formatted to correct colour in Excel (shows correctly in libreoffice calc)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM