将CSV文件导入Excel文件

问题描述 投票:0回答:1

我已经尝试了几种建议的方法来在Stack Overflow上执行此操作,到目前为止,没有一种方法起作用。我有一些格式不同的CSV文件,我希望将其导入Excel工作簿并添加带有一些公式的新工作簿。

以下是我尝试过的链接:Link1Link2Link3

我已经尝试了他们的建议,在最佳情况下什么也没有发生,在最坏的情况下,我会得到Null错误。文件名1:YYYY-MM-DD.csv格式1:

2019/09/04 00:00  32.85 17.94 21.04 0.00
2019/09/04 00:00  32.98 15.77 21.43 -0.02
2019/09/04 00:00  32.85 15.23 21.21 -0.09
2019/09/04 00:01  32.93 15.51 21.30 0.06
2019/09/04 00:01  32.96 15.54 21.45 0.36
2019/09/04 00:01  33.09 17.49 21.26 0.02
2019/09/04 00:01  34.74 17.34 21.17 0.00
2019/09/04 00:02  35.08 17.87 20.62 -0.06

FileName2:YYYY-MM-DD.csvFormate2:

2019/05/01 09:36  30.8,67.6
2019/05/01 09:37  28.8,57.6
2019/05/01 09:38  27.2,53.6
2019/05/01 09:39  27.3,53.4
2019/05/01 09:40  27.0,50.5
2019/05/01 09:41  27.8,54.8
2019/05/01 09:42  25.7,47.1
2019/05/01 09:43  25.8,49.3
2019/05/01 09:44  25.8,48.4
2019/05/01 09:45  26.0,50.0

FileName3:YYYYMMDD.csvFormate3:

2019/09/16 08:00 ,001896100BE3,26C,79RH,2,4,8
2019/09/16 08:01 ,001896100BE3,27C,77RH,2,4,7
2019/09/16 08:01 ,001896100BE3,27C,75RH,3,5,5
2019/09/16 08:02 ,001896100BE3,28C,74RH,2,4,5
excel python-3.x file
1个回答
0
投票

基本方法:

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

from contextlib import closing
from csv import reader
from xlsxwriter import Workbook

if __name__ == '__main__':

    # file2

    # open workbook
    workbook = Workbook('file2.xlsx')

    # add worksheet
    page1 = workbook.add_worksheet()

    with closing(open('file2.csv', 'r')) as csv_file:
        # read the csv file
        reader_orig = reader(csv_file, delimiter=' ')

        # iterate through the rows
        row = 0
        for el in reader_orig:
            res = dict()
            res['date'] = el[0]
            res['time'] = el[1]
            res['c1'] = el[3].split(',')[0]
            res['c2'] = el[3].split(',')[1]

            # fill in the result of reading to xlsx
            col = 0
            for item in res:
                page1.write(row, col, res[item])
                col += 1

            row += 1

    workbook.close()

data in excel

您可以看到其他情况here

© www.soinside.com 2019 - 2024. All rights reserved.