【问题标题】:openpyxl python - writing csv to excel gives 'number formatted as text'openpyxl python - 将 csv 写入 excel 会给出“格式化为文本的数字”
【发布时间】:2014-09-18 05:49:03
【问题描述】:

我编写了一个代码,通过 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"

*****更新***

谢谢,有帮助。我的问题是我的 csv 文件混合了文本和数字,没有任何定义引号。因此,只要没有错误,我就实现了以下将其从字符串更改为浮点数。

#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

【问题讨论】:

  • 这通常会起作用,尽管您可能还想查看.isnumeric() 和其他字符串方法。但是,我还假设特定列中的所有值都属于同一类型。

标签: python excel python-2.7 csv openpyxl


【解决方案1】:

您需要将 CSV 文件中的值转换为您需要的值。 CSV 文件中的所有值都是字符串。 ws.cell('%s%s'%(column_letter, (row_index + 1))).value = int(cell) 应该这样做。

顺便说一句。你可能想看看ws.append() 方法。

【讨论】:

    【解决方案2】:

    这是第一个谷歌结果,我花了比我愿意承认的更多的时间来做这个。我希望它对将来的人有所帮助。

    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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-08-04
      • 1970-01-01
      • 2023-01-18
      • 1970-01-01
      • 2017-09-06
      • 1970-01-01
      • 2014-05-25
      相关资源
      最近更新 更多