如何使用python和xlsxwriter将欧洲风格的时间转换为美国风格

2024-03-29 14:01:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一组形式为“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一直在我的公式前面添加一个@符号,我得到一个#名称?错误

screenshot of the excel page

有没有更好的方法来解决这个问题,或者有没有人能快速解决excel问题,我可以将其添加到我的代码中?谢谢


1条回答
网友
1楼 · 发布于 2024-03-29 14:01:18

以下是一种可能的方法,当使用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写操作移出你的循环,因为它们不会改变

相关问题 更多 >