2012-12-10 67 views
0

我是一名学生,没有很高的期限来完成这项工作。 接下来就是问题了。 我有部分代码:不知道用python-excel读取数据文件

import matplotlib.pyplot as plt 
from pylab import * 
import cmath 
def sf(prompt): 
""" """ 
    error_message = "Value must be integer and greater or equal than zero" 
    while True: 
     val = raw_input(prompt) 
     try: 
      val = float(val) 
     except ValueError: 
      print(error_message) 
      continue 
     if val <= 0: 
      print(error_message) 
      continue 
     return val 
def petrogen_elements(): 
    """Input and calculations the main parameters for 
    pertogen elements""" 
    print "Please enter Petrogen elements: \r" 
    SiO2 = sf("SiO2: ") 
    Al2O3= sf("Al2O3: ") 
    Na2O = sf("Na2O: ") 
    K2O = sf("K2O: ") 

    petro = [SiO2,TiO2,Al2O3,]      

    Sum = sum(petro) 

    Alcal = Na2O + K2O 
    TypeA lcal= Na2O/K2O 
    Ka= (Na2O + K2O)/ Al2O3 

    print '-'*20, "\r Alcal: %s \r TypeAlcal: %s \ 
    \r Ka: %s \r" % (Alcal, TypeAlcal,Ka,) 

petrogen_elements() 

所以问题是下一个。我必须加载并读取excel文件并读取其中的所有数据。该程序后,必须 计算例如Alcaline,Alcaline等 Excel文件的类型只有这种结构

1 2  3  4 5   
1 name1 SiO2 Al2O3 Na2O K2O 
2  32 12 0.21 0.1 
3 name2 SiO2 Al2O3 Na2O K2O 
4  45 8 7.54 5 
5 name3 SiO2 Al2O3 Na2O K2O 
6. … …. …. … 
… 
… 

所有excel文件只有5列和无限行。 用户可以选择输入数据或导入excel文件。 我已完成的第一部分工作,但它保持很大部分 最后,我需要读取所有文件并计算值。

我会为一些建议

+1

如果您可以将excel文件转换为csv,您可以使用内置的['csv'](http://docs.python.org/2/library/csv.html )模块。 – l4mpi

回答

1

有本网站http://www.python-excel.org/,列出了所有主要的Python的Excel相关的库非常感激。 我个人已经尝试过XLRD--第一个被列出 - 并且发现它很棒,它有一个整洁的文档。

在埃及举行总统选举时,我也做了一些工作,因为我们需要导入到MySQL数据库中的Excel表中有很多数据。我发表的代码在Github上:https://github.com/mos3abof/egypt-elections-misc

首先安装xlrd

你会想出脚本应该是这样的:

from xlrd import * 
## Opening the excel file 
book = open_workbook('excel_file.xls') 

## Reading the sheet we need 
## Most probably the data will be on the first sheet, 
## otherwise this needs to be updated 
our_sheet = book.sheet_by_index(0) 

## Get the rows number 
rowcount = our_sheet.nrows 

## Looping over sheet rows 
for i in range(rowcount -1): 
    ## Get the data in the row 
    our_row = our_sheet.row_slice(i+1) 

    ## Access each row by index and do whatever you like with it 
    ## Since you have 5 columns, the index will range from 0 - 4 
    print our_row[0] 
    print our_row[1] 
    print our_row[2] 
    print our_row[3] 
    print our_row[4] 

你可以找到我所提到的脚本的工作示例以上在这个文件中:https://github.com/mos3abof/egypt-elections-misc/blob/master/elections_import_excel.py

+0

非常感谢你)这是真的帮助) –

+0

很高兴我可以帮助,你会考虑标记我接受的答案,请吗? :) –

相关问题