使用python将xlsx文件复制到另一个文件时出现问题



所以这对你们中的一些人来说可能看起来很傻,但我是python的新手,所以我不太知道发生了什么,

我需要删除excel表格的第一列和前7行,在查找后,我在这个网站上发现,打开另一个文件,只处理我需要的文件会更容易,所以我尝试了这样的

import openpyxl

#File to be copied
wb = openpyxl.load_workbook(r"C:Usersgb2gaetNova pastaold.xlsx") #Add file name
sheet = wb["Sheet1"]#Add Sheet name

#File to be pasted into
template = openpyxl.load_workbook(r"C:Usersgb2gaetNova pastanew.xlsx") #Add file name
temp_sheet = wb["Sheet1"] #Add Sheet name

#Takes: start cell, end cell, and sheet you want to copy from.
def copyRange(startCol, startRow, endCol, endRow, sheet):
rangeSelected = []
#Loops through selected Rows
for i in range(startRow,endRow + 1,1):
#Appends the row to a RowSelected list
rowSelected = []
for j in range(startCol,endCol+1,1):
rowSelected.append(sheet.cell(row = i, column = j).value)
#Adds the RowSelected List and nests inside the rangeSelected
rangeSelected.append(rowSelected)

return rangeSelected

#Paste data from copyRange into template sheet
def pasteRange(startCol, startRow, endCol, endRow, sheetReceiving, copiedData):
countRow = 0
for i in range(startRow,endRow+1,1):
countCol = 0
for j in range(startCol,endCol+1,1):

sheetReceiving.cell(row = i, column = j).value = copiedData[countRow][countCol]
countCol += 1
countRow += 1

def createData():
print("Processing...")
selectedRange = copyRange(2,8,17,100000,sheet)
pasteRange(1,1,16,100000,temp_sheet,selectedRange)
wb.save("new.xlsx")
print("Range copied and pasted!")

程序运行时没有任何错误,但当我查看新表时,它完全是空的,我缺少什么?如果你们能想出任何更简单的解决方案来删除行和列,我愿意通过更改所有代码

我建议通过panda来执行此操作。使用pandas.read_excel((函数将excel文件导入数据帧,然后使用dataframe.drop((函数删除所需的列和行,然后使用to_excel函数将数据帧导出到新的excel文件。

代码看起来像这样:

import pandas as pd
df = pd.read_excel(r"C:Usersgb2gaetNova pastaold.xlsx")
#careful with how this imports different sheets. If you have multiple,
#it will basically import the excel file as a dictionary of dataframes
#where each key-value pair corresponds to one sheet.
df = df.drop(columns = <columns you want removed>)
df.to_excel('new.xlsx')
#this will save the new file in the same place as your python script

以下是一些关于这些功能的文档:

read_excel((:https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.read_excel.html?highlight=read_excel

Drop((:https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.drop.html

to_excel((:https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.to_excel.html?highlight=to_excel#pandas.DataFrame.to_excel

最新更新