使用Pyexcel处理Excel数据

这是一个Python问题:

你好我正在做一个networking应用程序,它从一个电子表格(.csv)接收数据转化为整数从。 评估这些值,返回这些值,并将这些数据写入表格的第4列,每行。 正如你可以看到我的代码:

import fileinput import csv import pyexcel as pe records = pe.iget_records(file_name="test.xlxs") cho = raw_input("\nStart Forecaster on file?:<1/0>") if cho == 1: for record in records: rem = record[i,0] sold1 = record[i,1] sold2 = record[i,2] rem = int(rem) sold1 = int(sold1) sold2 = int(sold2) result = forecast(rem,sold1,sold2) record[i,4] = result print "Forecast Complete! Please check the file!" else: quit() def calculate(rem,sold1,sold2): result = ((l+t)/2)*3 return result def forecast(rem,sold1,sold2): if (rmn == 0 and sold1 == 0 and sold2 ==0): #All ZERO return 15 elif (rmn == 0 and sold1 == 0 and sold2 < 10): #ALL FOR ONE PRODUCT VALUE return sold2*3 elif (rmn == 0 and sold1 < 10 and sold2 ==0): return sold1*3 elif (rmn < 10 and sold1 == 0 and sold2 == 0): return rmn*3 #END FOR ONE PRODUCT VALUE elif (rmn>= 10 and sold1>=10 and sold2>=10): if((rmn/3)>=(sold1+10) or (rmn/3)>=(sold1+10)): return 0 else: return calculate(rmn,sold1,sold2)-rmn elif (rmn<10 and sold1<10 and sold2<10): return calculate(rmn,sold1,sold2) elif (rmn == 0 and sold1>=10 and sold2>=10): return calculate(rmn,sold1,sold2) else: return sold1 

…没有错误,但它没有任何影响的CSV文件。 有任何想法吗? 另外在print "Forecast Complete! Please check the file!" ..当我运行程序它不会到达那里意味着必须有错误的循环? 我正在搞清楚 但我也想要求帮助。

原始文件:

 1 2 3 1 2 3 1 2 3 

我想要发生的事情:

 1 2 3 result(digits) 1 2 3 result(digits) 1 2 3 result(digits) 

简短的回答

pyexcel.iget_records返回一个字典列表,适用于带有标题行的数据。 'records.save_as'将不起作用,因为返回的数据结构是一个标准的Python列表,它自然不具有save_asfunction。

pyexcel.Sheet实例将有一个save_as函数,但是'pyexcel.get_sheet'应该用在你的代码中。 或者pyexcel.save_as ,模块级别的函数可以将一个数组保存到一个文件中。 看到这里的例子 。

样品解决scheme

 >>> import pyexcel as p >>> sheet = p.get_sheet(file_name='test.xlsx') # pip install pyexcel-xlsx >>> sheet Sheet 1: +---+---+---+ | 1 | 2 | 3 | +---+---+---+ | 1 | 2 | 3 | +---+---+---+ | 1 | 2 | 3 | +---+---+---+ >>> for row in sheet: ... print row ... [1, 2, 3] [1, 2, 3] [1, 2, 3] >>> results = [] >>> for row in sheet: ... results.append(sum(row)) # <- do your own forcast here ... >>> results [6, 6, 6] >>> sheet.column += results >>> sheet Sheet 1: +---+---+---+---+ | 1 | 2 | 3 | 6 | +---+---+---+---+ | 1 | 2 | 3 | 6 | +---+---+---+---+ | 1 | 2 | 3 | 6 | +---+---+---+---+ >>> sheet.save_as('new.csv') 

长答案

pyexcel帮助您在一个class轮中获得python数据结构。 有4个函数 :get_array,get_dict,get_records和get_book_dict。 提供了两个stream式函数来处理更大的数据大小:iget_array和iget_records 。 假设开发人员只需要数据进行分析。

pyexcel提供了两个自定义函数来帮助您操作数据: get_sheet和get_book。 前者返回pyexcel.Sheet ,后者返回pyexcel.Book 。 假设开发人员需要操作行,列和表单,然后将表单/书籍保存回Excel文件。

这样说,但是,通用的Python数据结构可以很容易地存储为一个Excel文件。 以下是模块级别的三个保存function :save_as和save_book_as。 下面是如何将数组保存到xls文件的示例。

与pandas相比, pyexcel是一个重量轻,易于安装,易于理解和基于组件的excel数据处理软件包。 然而,它并不是要取代大pandas,而是为了减less复杂性的数据分析任务。

与openpyxl和xlsxwriter相比, pyexcel让您专注于数据,而不是文件格式,您可以在其中重新使用代码来处理ods,xls和csv文件格式而无需更改代码