将列表写入excel

时间:2014-07-02 04:16:14

标签: python excel python-2.7

我正在尝试执行以下操作:

对于Col A中的每个条目,如果该条目在同一个Col A中重复出现,则将其在Col E中的所有值相加。

然后,只将Col E中的(添加的)值写入另一个Excel工作表。每个Col A条目应具有与其对应的所有Col E值。

但是,我只能为最后一行创建输出表。

Source excel sheet

这是我写的代码,

#! /usr/bin/env python

from xlrd import open_workbook
from tempfile import TemporaryFile
from xlwt import Workbook

wb = open_workbook('/Users/dem/Documents/test.xlsx')
wk = wb.sheet_by_index(0)

for i in range(wk.nrows):
    a = str(wk.cell(i,0).value)    
    b = []
    e = []

    for j in range(wk.nrows):
        c = str(wk.cell(j,0).value)
        d = str(wk.cell(j,4).value)
        if a == c:
            b.append(d)
    print b
    e.append(b)

book = Workbook()
sheet1 = book.add_sheet('sheet1')

n = 0
for n, item in enumerate(e):
    sheet1.write(n,0,item)
    n +=1

book.save('/Users/dem/Documents/res.xls')
book.save(TemporaryFile())

Erred enter image description here结果表(我的):

2 个答案:

答案 0 :(得分:1)

我认为您应该期待csv.writerdialect='excel'一起使用。本文档中有一个关于使用情况的示例。我认为如果您不需要像您的情况那样的大功能,这只是使用excel的最简单方法。

答案 1 :(得分:1)

代码中的评论。

#! /usr/bin/env python

from xlrd import open_workbook
from tempfile import TemporaryFile
from xlwt import Workbook
import copy

wb = open_workbook('C:\\Temp\\test.xls')
wk = wb.sheet_by_index(0)

# you need to put e=[] outside the loop in case they are reset to empty list every loop
# e is used to store final result
e = []
# f is used to store value in Col A which means we only record value once
f = []

for i in range(wk.nrows):

    b = []
    temp = None

    a = str(wk.cell(i,0).value)    

    #here we only record value once
    if a in f:
        continue

    #here you should start from i+1 to avoid double counting
    for j in range(i+1, wk.nrows):
        c = str(wk.cell(j,0).value)

        if a == c:
            # you can put operations here in order to make sure they are executed only when needed

            d = str(wk.cell(j,4).value)
            k = str(wk.cell(i,4).value)

            f.append(a)

            # record all the value in Col E
            b.append(k)
            b.append(d)

            # you need to use deepcopy here in order to get accurate value
            temp = copy.deepcopy(b)

    # in your case, row 5 has no duplication, temp for row 5 will be none, we need to avoid adding none to final result 
    if temp:
        e.append(temp)

book = Workbook()
sheet1 = book.add_sheet('sheet1')

n = 0
for n, item in enumerate(e):
    sheet1.write(n,0,item)
    # you don't need n+=1 here, since n will increase itself

book.save('C:\\Temp\\res.xls')
book.save(TemporaryFile())