Excel单元格值填充0

下面的代码部分

import collections import csv import sys with open("321.csv","r") as f: cr = csv.reader(f,delimiter=",") d=collections.defaultdict(lambda : list()) header=next(cr) # read title. Retrieve the next item from the iterator by calling its __next__() method. for r in cr: d[r[0]].append(r[1]) # fill dict with open("sorted output.csv","w") as f: cr = csv.writer(f,sys.stdout, lineterminator='\n') od = collections.OrderedDict(sorted(d.items()))#sort items based on dictionary key value for k,v in od.items(): #The method items() returns a list of dict's (key, value) tuple pairs v = [ord(i) for i in v] # convert letters into numbers cr.writerow(v) 

给我这个输出:

在这里输入图像说明

我想填充区域中的所有空单元格(A1 :: X30)(每次填充0的单元格都是按最大行长度定义的,例如,如果最大的行元素直到列Y应该填充0的空单元格将在区域(A1 :: Y30))

你能帮我吗?

我没有testing,但也许这个?

 import collections import csv import sys max_len = 0 with open("321.csv","r") as f: cr = csv.reader(f,delimiter=",") d=collections.defaultdict(lambda : list()) header=next(cr) # read title. Retrieve the next item from the iterator by calling its __next__() method. for r in cr: d[r[0]].append(r[1]) # fill dict max_len = max(len(d[r[0]]), max_len) with open("sorted output.csv","w") as f: cr = csv.writer(f,sys.stdout, lineterminator='\n') od = collections.OrderedDict(sorted(d.items()))#sort items based on dictionary key value for k,v in od.items(): #The method items() returns a list of dict's (key, value) tuple pairs v = [ord(i) for i in v] + [0]*(max_len - len(v)) # convert letters into numbers cr.writerow(v) 

我不太确定,如果我正确理解你的问题。 这是一个尝试:

要创build一个只有0的xls文件,可以使用pandas和numpy,如下所示:

 import pandas as pd import numpy as np import io number_of_rows = 30 number_of_columns = 24 # Create a dataframe of 0's in the dimension you define above df = pd.DataFrame(np.array([np.zeros(number_of_columns) for i in range(number_of_rows)])) # Give out as xls file df.to_excel('output.xls', index=False) 

如果你想让某些单元格为非零而其余单元格为零,那么可以使用类似下面这样的函数来覆盖(在df.to_excle之前):

 df.set_values(row,column,value) 

希望有一点帮助。