简体   繁体   English

Python - 以CSV格式从Excel电子表格打印单个单元格

[英]Python - Printing individual cells from an Excel spreadsheet in CSV format

I have an excel spreadsheet saved as a CSV file, but cannot find a way to call individual values from cells into Python using the CSV module. 我有一个excel电子表格保存为CSV文件,但找不到使用CSV模块将单个值从单元格调用到Python的方法。 Any help would be greatly appreciated 任何帮助将不胜感激

There is also a Python library capable of reading xls data. 还有一个能够读取xls数据的Python库。 Have a look at python-xlrd . 看看python-xlrd

For writing xls data, you can use python-xlwt . 要编写xls数据,可以使用python-xlwt

The csv module provide readers that iterate over the rows of a csv file - the rows are lists of strings. csv模块为读者提供迭代csv文件行的行 - 是字符串列表。 One way to get access to individual cells would be to: 获取单个单元格的一种方法是:

Read the entire file in as a list of lists 以列表列表的形式读取整个文件

import csv
with open('test.csv', 'r') as f:
    reader = csv.reader(f)
    the_whole_file = list(reader)

Then access the individual cells by indexing into the_whole_file . 然后通过索引到the_whole_file访问各个单元格。 The first index is the row and the second index is the column - both are zero based. 第一个索引是行,第二个索引是列 - 两者都是零。 To access the cell at the second row, fourth column: 要访问第二行,第四列的单元格:

row = 1
column = 3
cell_R1_C3 = the_whole_file[row][column]

print cell_R1_C3

If you have the excel file as a CSV, you can use csv.reader 如果您将Excel文件作为CSV,则可以使用csv.reader

import csv
myFilePath = "/Path/To/Your/File"
with open(myFilePath,'rb') as csvfile:
    reader = csv.reader( csvfile, delimiter=',' )
    for row in reader:
        # 'row' has all the cells (thanks to wwii for the fix!). Get the first 4 columns
        a, b, c, d = row[:4]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM