首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >不知道用python-excel读取数据文件

不知道用python-excel读取数据文件
EN

Stack Overflow用户
提问于 2012-12-11 00:44:05
回答 1查看 1.3K关注 0票数 0

我是一名学生,没有做这项工作的经验。所以接下来就是问题了。我有一部分代码:

代码语言:javascript
复制
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文件仅具有此结构

代码语言:javascript
复制
   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文件。第一部分的工作,我已经做了,但它仍然是很大的一部分,最后,我需要读取所有文件和计算值。

如果你能给我一些建议,我将不胜感激

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2012-12-11 01:12:54

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

我也做了一些工作,而总统选举在埃及举行,因为有大量的数据在excel表中,我们需要导入到mysql数据库。我已经在Github上发布了代码:https://github.com/mos3abof/egypt-elections-misc

首先安装xlrd

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

代码语言:javascript
复制
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

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/13805274

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档