我是一名Python初學者,需要幫助。我正在使用Python 2.7,我試圖檢索excel文件的單元格值並將其存儲到csv文件中。我的代碼如下:如何使用openpyxl獲取單元格的實際值?
import os, openpyxl, csv
aggname = "deu"
wb_source = openpyxl.load_workbook(filename, data_only = True)
app_file = open(filename,'a')
dest_file = csv.writer(app_file, delimiter=',', lineterminator='\n')
calib_sheet = wb_source.get_sheet_by_name('Calibration')
data = calib_sheet['B78:C88']
data = list(data)
print(data)
for i in range(len(data)):
dest_file.writerow(data[i])
app_file.close()
在我的csv文件,我得到這個,而不是實際值(在我的情況,例如:SFCG,99103)。
<Cell Calibration.B78>,<Cell Calibration.C78>
<Cell Calibration.B79>,<Cell Calibration.C79>
<Cell Calibration.B80>,<Cell Calibration.C80>
<Cell Calibration.B81>,<Cell Calibration.C81>
<Cell Calibration.B82>,<Cell Calibration.C82>
<Cell Calibration.B83>,<Cell Calibration.C83>
<Cell Calibration.B84>,<Cell Calibration.C84>
<Cell Calibration.B85>,<Cell Calibration.C85>
<Cell Calibration.B86>,<Cell Calibration.C86>
<Cell Calibration.B87>,<Cell Calibration.C87>
<Cell Calibration.B88>,<Cell Calibration.C88>
我試圖設置DATA_ONLY =真,打開Excel文件時,在回答類似的問題建議,但它並沒有解決我的問題。
---------------編輯-------------
考慮到前兩個答案,我得到了(謝謝! ),我試過幾件事情:
for i in range(len(data)):
dest_file.writerows(data[i].value)
我收到此錯誤信息:
for i in range(len(data)):
dest_file.writerows(data[i].values)
Traceback (most recent call last):
File "<ipython-input-78-27828c989b39>", line 2, in <module>
dest_file.writerows(data[i].values)
AttributeError: 'tuple' object has no attribute 'values'
然後我嘗試這個:
for i in range(len(data)):
for j in range(2):
dest_file.writerow(data[i][j].value)
,然後我有以下錯誤信息:
for i in range(len(data)):
for j in range(2):
dest_file.writerow(data[i][j].value)
Traceback (most recent call last):
File "<ipython-input-80-c571abd7c3ec>", line 3, in <module>
dest_file.writerow(data[i][j].value)
Error: sequence expected
那麼,我想這一點:
import os, openpyxl, csv
wb_source = openpyxl.load_workbook(filename, data_only=True)
app_file = open(filename,'a')
dest_file = csv.writer(app_file, delimiter=',', lineterminator='\n')
calib_sheet = wb_source.get_sheet_by_name('Calibration')
list(calib_sheet.iter_rows('B78:C88'))
for row in calib_sheet.iter_rows('B78:C88'):
for cell in row:
dest_file.writerow(cell.value)
只有收到此錯誤信息:
Traceback (most recent call last):
File "<ipython-input-81-5bed62b45985>", line 12, in <module>
dest_file.writerow(cell.value)
Error: sequence expected
對於「序列預期「的錯誤我想蟒蛇期望一個列表而不是一個單元格,所以我這樣做:
個進口操作系統,openpyxl,CSV
wb_source = openpyxl.load_workbook(filename, data_only=True)
app_file = open(filename,'a')
dest_file = csv.writer(app_file, delimiter=',', lineterminator='\n')
calib_sheet = wb_source.get_sheet_by_name('Calibration')
list(calib_sheet.iter_rows('B78:C88'))
for row in calib_sheet.iter_rows('B78:C88'):
dest_file.writerow(row)
沒有錯誤消息,但我只得到在CSV文件中的單元格的引用,並改變它dest_file.writerow(row.value)使我回元組錯誤。
我顯然還需要你的幫助!
謝謝你,但我得到以下錯誤,當我申請你的建議: 回溯(最近通話最後一個): '文件「」,2號線,在 dest_file。作者(data [i] .value)' AttributeError:'元組'對象沒有屬性'值' –
dessa
Hey dessa ....對不起,它沒有爲你工作,但很高興你完成了..從你身上學到了一些東西 –