我非常沮丧地尝试编写代码来迭代 .xls(或 .xlsx)电子表格,其中每张纸都是一年,编辑每张纸以删除第 1-4,6 行和 72-150 行,删除第一列,然后将该工作表导出为 csv。所以我应该每张(年)都有一个 csv。我尝试过使用 pandas、xlrd、openpyxl,但每一行都不断出现错误。有人能帮我吗?额外包最少的最简单方法是什么?不断获取该列表不可调用或字符串或错误的索引。请帮忙。
欣赏它!
import openpyxl
import csv
workbook = openpyxl.load_workbook("C:/Users/example.xlsx")
worksheet = workbook.sheetnames
print(worksheet)
for sheet in worksheet:
mrts_worksheet['B5'] = "Diff Label"
sheet.delete_rows(mrts_worksheet.delete_rows(72, 100))
sheet.delete_rows(mrts_worksheet.delete_rows(6, 1))
sheet.delete_rows(mrts_worksheet.delete_rows(1, 4))
sheet.delete_cols(1,1)
with open("C:/Users/example"+ sheet +".csv", "w", newline="") as file_handle:
csv_writer = csv.writer(file_handle)
for row in sheet.iter_rows():
csv_writer.writerow([cell.value for cell in row])
file_handle.close()
为了使您的代码示例能够根据描述中提供的详细信息工作,需要更改为如下内容;
你的删除方法很好,从最后几行开始删除,向上移动到第1行。你的代码有
delete_rows(72, 100)
,这将删除不符合要求的72到171行,72-150,所以将其更改为delete_rows(72, 79)
.“mrts_worksheet”部分已被删除。我不知道这张表的目的是什么,也不知道它应该如何与删除其他表中的行一起工作。即使将值写入工作表循环中的单元格 B5 也会显得浪费,
mrts_worksheet['B5'] = "Diff Label"
,因为您只需要执行此操作一次,而不是为工作簿中的每个工作表执行一次,因为它不会更改。 import openpyxl
import csv
workbook = openpyxl.load_workbook("data.xlsx")
worksheet = workbook.worksheets # List of Worksheet objects
print(worksheet)
for sheet in worksheet: # 'sheet' is a worksheet
sheet.delete_rows(72, 79) # Delete rows 72 - 150, start at row 72 and delete the next 79 rows
sheet.delete_rows(6, 1) # Delete row 6, start at row 6 and delete that row only
sheet.delete_rows(1, 4) # Delete rows 1 - 4, start at row 1 and delete the next 4 rows
sheet.delete_cols(1, 1) # Delete column 'A'
### Create csv file name using sheet name (title)
with open("example" + sheet.title + ".csv", "w", newline="") as file_handle:
csv_writer = csv.writer(file_handle)
for row in sheet.iter_rows():
csv_writer.writerow([cell.value for cell in row])
file_handle.close()