从excel读取数据并以CSV格式写入文件 - Python

时间:2017-11-02 20:38:16

标签: python excel csv xlrd

我有一张excel表,其中有5行5列,其中包含以下值:

Time   Launch   Login    Password    Signout
00:01   1.26     1.56      5.24        12.3
00:02   1.22     1.55      5.34        2.35
00:03   1.36     1.53      1.24        2.13
00:05   1.46     1.26      2.24        1.32

如何将上述数据转换为csv格式并将其写入文本文件。我能够从excel中读取它们,但是当我写作时,它们都会合并。

输出格式:

Time,Launch,Login,Password,Signout
00:01,1.26,1.56,5.24,12.3
00:02,1.22,1.55,5.34,2.35
00:03,1.36,1.53,1.24,2.13
00:05,1.46,1.26,2.24,1.32

我的代码:

workbook3 = xlrd.open_workbook('C:\Users\aa\Desktop\Report3.xls', logfile=open(os.devnull, 'w'))
worksheet3 = workbook3.sheet_by_index(0)
num_cols3 = worksheet3.ncols
num_rows3 = worksheet3.nrows
for row_index3 in range(0, num_rows3):
    for col_index3 in range(0, num_cols3):
        cell_val= worksheet3.cell(row_index3, col_index3).value
        with open("C:\Users\aa\Desktop\outputfile.txt", 'a') as f:
            f.write(cell_val)
print "Write Completed" 

请指导。

3 个答案:

答案 0 :(得分:2)

您可以尝试使用pandas。它让你想做的事变得非常轻松。

import pandas as pd
filename = "filename.xlsx"
data = pd.read_excel(filename).to_csv(filename.replace(".xlsx", ".csv"))

另外,IMO更容易收集二维数组中的所有数据。像

这样的东西
data = []
for row_index3 in range(0, num_rows3):
    row = []
    for col_index3 in range(0, num_cols3):
        row.append(worksheet3.cell(row_index3, col_index3).value)
    data.append(row)
with open("C:\Users\aa\Desktop\outputfile.txt", 'w') as f: 
    f.write("\n".join(','.join(map(str, row)) for row in data))
print "Write Completed" 

答案 1 :(得分:0)

使用python运行时https://docs.python.org/2/library/csv.html

中的模块csv
import csv
with open('eggs.csv', 'wb') as csvfile:
    spamwriter = csv.writer(csvfile, delimiter=' ',
                            quotechar='|', quoting=csv.QUOTE_MINIMAL)
    spamwriter.writerow(['Spam'] * 5 + ['Baked Beans'])
    spamwriter.writerow(['Spam', 'Lovely Spam', 'Wonderful Spam'])

答案 2 :(得分:0)

我能够得到答案。代码如下。

workbook3 = xlrd.open_workbook('C:\Users\aa\Desktop\Report3.xls', logfile=open(os.devnull, 'w'))
worksheet3 = workbook3.sheet_by_index(0)
num_cols3 = worksheet3.ncols
num_rows3 = worksheet3.nrows
f = open("C:\Users\aa\Desktop\outputfile.txt", 'a')
for row_index3 in range(0, num_rows3):
    for col_index3 in range(0, num_cols3):
        cell_val= worksheet3.cell(row_index3, col_index3).value
        f.write(cell_val+",")
    f.write("\n")       
print "Write Completed"

但是这里的一个问题是,即使在行的最后一个值之后,也会出现逗号,。知道怎么过来吗?