我是python的新手,需要你的帮助。我正在尝试使用pyxl编写在excel中迭代特定列的代码
V = |(P5->P8 X P5->P6) * P5->P1|
P1 = ( [-17/12] , [11/36], [-65/36])
P5 = ([-11/12], [-7/36], [-47/36])
P6 = ([-2/3],[-1/9],[-8/9])
P8 = ([-5/4],[-1/12],[-17/12])`
在上面的示例中,我必须转到第J列并显示列中的所有值。
请帮我解决这个问题。
另外,我在excel表中重复了相同的列名。例如" Sample"列名在B2和J2中都可用。但是我想得到J2的所有列信息。
请让我知道如何解决这个问题......
谢谢..请回复
答案 0 :(得分:0)
由于你是python的新手,你应该learn to read the documentation。有大量的模块可供使用,如果您先付出努力,它对您来说会更快,对我们其他人来说也更容易。
import openpyxl
from openpyxl.utils import cell as cellutils
## My example book simply has "=Address(Row(),Column())" in A1:J20
## Because my example uses formulae, I am loading my workbook with
## "data_only = True" in order to get the values; if your cells do not
## contain formulae, you can omit data_only
workbook = openpyxl.load_workbook("workbook.xlsx", data_only = True)
worksheet = workbook.active
## Alterntively: worksheet = workbook["sheetname"]
## A container for gathering the cell values
output = []
## Current Row = 2 assumes that Cell 1 (in this case, J1) contains your column header
## Adjust as necessary
column = cellutils.column_index_from_string("J")
currentrow = 2
## Get the first cell
cell = worksheet.cell(column = column, row = currentrow)
## The purpose of "While cell.value" is that I'm assuming the column
## is complete when the cell does not contain a value
## If you know the exact range you need, you can either use a for-loop,
## or look at openpyxl.utils.cell.rows_from_range
while cell.value:
## Add Cell value to our list of values for this column
output.append(cell.value)
## Move to the next row
currentrow += 1
## Get that cell
cell = worksheet.cell(column = column, row = currentrow)
print(output)
""" output: ['$J$2', '$J$3', '$J$4', '$J$5', '$J$6', '$J$7',
'$J$8', '$J$9', '$J$10', '$J$11', '$J$12', '$J$13', '$J$14',
'$J$15', '$J$16', '$J$17', '$J$18', '$J$19', '$J$20']