我一直在使用帶有多張作業表的 excel 書。示例我有學生串列,每個學生的唯一編號和該學生所從事的多個科目及其出勤率如下所示:作業
表編號 1 - 18CS45
| 美國海軍 | 姓名 | 參加 | 總計 | 百分比 | |------------|--------|----------|--------|--------- | | 1US22CS001 | 強尼 | 10 | 10 | 100 | | 1US22CS002 | 燈芯 | 5 | 10 | 50 |
表號 2 - 18CS56
| 美國海軍 | 姓名 | 參加 | 總計 | 百分比 | |------------|--------|----------|--------|--------- | | 1US22CS001 | 強尼 | 10 | 10 | 100 | | 1US22CS002 | 燈芯 | 5 | 10 | 50 |
我想根據USN從表 1 和表 2 中提取資料行,并將其保存為每個學生的 CSV。如何使用 python openpyxl或csv包來實作這一點
uj5u.com熱心網友回復:
有一種使用函式的基本方法,你可以試試這個。我也解釋了代碼的每一部分。
- 在這種情況下,我使用了csv庫
import csv
def pull_data(sheet1, sheet2, usn_number):
# Open the first sheet
with open(sheet1, 'r') as sheet1_file:
sheet1_reader = csv.reader(sheet1_file)
# Open the second sheet
with open(sheet2, 'r') as sheet2_file:
sheet2_reader = csv.reader(sheet2_file)
# Open the csv file
with open('data.csv', 'w') as csv_file:
csv_writer = csv.writer(csv_file)
# Loop through the first sheet
for row in sheet1_reader:
# Check if the usn number is in the first sheet
if usn_number in row:
# If it is, add the row to the csv file
csv_writer.writerow(row)
# Loop through the second sheet
for row in sheet2_reader:
# Check if the usn number is in the second sheet
if usn_number in row:
# If it is, add the row to the csv file
csv_writer.writerow(row)
pull_data('sheet1.csv', 'sheet2.csv', 'USN_NUMBER')
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/487943.html
上一篇:將.csv檔案讀入二維陣列
