0

使用 openpyxl 读取 excel 文件并将详细信息提取到新的 .txt 文件中

我是openpyxl的新手,昨天才开始。我需要从本地存储的 excel 文件中提取数据,该 excel 文件有 500 多行和 50 多列。我想将一些特定的单元格或列或行提取到 .txt 和 .csv 文件中。

我找不到在此代码中添加的错误在哪里

from openpyxl import *
import os    

path = 'F:\\mis'
files = [i for i in os.listdir(path) if i.endswith('.xlsx')]

for f in files:
     wb = load_workbook(os.path.join(path, f))
     for row in wb['newxl.xlsx'].rows:
         with open(row[2].value+'.txt', 'w') as outfile:
              outfile.write(row[0].value)```
4

2 回答 2

1

更新的答案

import openpyxl
import csv
      
roster = openpyxl.load_workbook('roster.xlsx')
sheet = roster.active
col = csv.writer(open("new_roster.csv",'w',newline=""))

st_id = int(input("Enter student ID: "))
for row in sheet.rows:
    if row[0].value == st_id:
        col.writerow([cell.value for cell in row])
print("File created!")

更新 2

这是您从特定列获取值的方式:

import openpyxl
roster = openpyxl.load_workbook('roster.xlsx')  
sheet = roster.active
col = sheet['B']  

for x in range(len(col)): 
    print(col[x].value) 

更新 3

从列返回特定值:

import openpyxl

roster = openpyxl.load_workbook('roster.xlsx')  
sheet = roster.active

col = sheet['B']  # <-- change the column according to your file
val = input("Enter value: ")
for c in range(len(col)): 
    if val == col[c].value:
        print(f'Found {col[c].value}!')
于 2022-01-03T11:33:20.653 回答
0
import pandas as pd
df=pd.read_excel("F:\\mis\\CASHE.xlsx")
cus_id=input("Please enter your customer id:")
cashe=['customer_id', 'customer_name', 'login_email_id', 'login_source', 'New_date', 'customer_status_name']

if cus_id == '':
    df1=df[cashe]
else:
    df1=df[cashe].loc[df['customer_id']==int(cus_id)]

df1.to_csv('Cashe1.csv')
print("csv printed with values")
于 2022-01-07T11:30:41.070 回答