【问题标题】:How to convert from european style time to us style using python and xlsxwriter如何使用 python 和 xlsxwriter 从欧洲风格时间转换为美国风格
【发布时间】:2021-09-20 07:07:43
【问题描述】:

我有一组格式为“22,4”而不是“22.4”的温度。我是 Python 新手(几天前刚开始),正在编写一个程序来将 csv 文件转换为 xlsx 文件并绘制一些数据。

文件最初用分号分隔。目前我已经适配了一组嵌套的for循环来编写xlsx文件,但是温度数据如前所述。

def graph_file():
    workbook = xlsxwriter.workbook.Workbook("New File.xlsx", {'strings_to_numbers': True})
    for file in files:
        sheet = workbook.add_worksheet("Sheet1")
        with open(file) as f:
            reader = csv.reader(f, delimiter=";")
            for r, row in enumerate(reader):
                for c, val in enumerate(row):
                    one_plus = r + 1
                    sheet.write(r, c, val)
                    sheet.write("AZ1", "Time")
                    sheet.write("AR1", "Temperature")
                    sheet.write("AZ" + str(one_plus), str(datetime.timedelta(seconds=r)))
                    sheet.write('AT' + str(one_plus), '=NUMBERVALUE(AQ' + str(one_plus) + ', ",", ".")')

这是我现在可以使用的,但 Excel 不断在我的公式前面添加一个 @ 符号,我得到一个 #NAME?错误。

有没有更好的方法来做到这一点,或者有人可以快速解决我可以添加到我的代码中的 excel 问题吗?谢谢

【问题讨论】:

  • CSV 文件中的数字是否使用逗号或句号/句点作为小数点?

标签: python excel csv xlsx xlsxwriter


【解决方案1】:

这是一种可能的方法,当使用csv.reader() 阅读时,所有内容都将是一个字符串,您可以根据需要将这些转换为数字:

def graph_file():
    workbook = xlsxwriter.workbook.Workbook("New File.xlsx", {'strings_to_numbers': True})
    
    for file in files:
        sheet = workbook.add_worksheet("Sheet1")
        sheet.write("AZ1", "Time")
        sheet.write("AR1", "Temperature")
        
        with open(file) as f:
            reader = csv.reader(f, delimiter=";")
            
            for r, row in enumerate(reader):
                print(row)

                for c, val in enumerate(row):
                    if r > 0:
                        if ',' in val:
                            val = float(val.replace(',', '.'))
                        else:
                            val = int(val)
                        
                    one_plus = r + 1
                    sheet.write(r, c, val)
                    sheet.write("AZ" + str(one_plus), str(datetime.timedelta(seconds=r)))
                    sheet.write('AT' + str(one_plus), '=NUMBERVALUE(AQ' + str(one_plus) + ', ",", ".")')
                    
        workbook.close()

这会忽略标题行,然后将任何值转换为整数。如果看到逗号,则将其替换为句点并将字符串转换为浮点数。

那么=NUMBERVALUE() 就不需要了。

我会将您的 AZ1AR1 写入您的循环之外,因为它们不会改变。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-13
    相关资源
    最近更新 更多