Python|如何将数据从一张excel表复制到另一张
在本文中,我们将学习如何使用Python中的 openpyxl 模块将数据从一个 Excel 工作表复制到目标 Excel 工作簿。
为了处理 excel 文件,我们需要openpyxl
,这是一个Python库,用于读取、写入和修改 excel(扩展名为 xlsx/xlsm/xltx/xltm)文件。可以使用以下命令安装它:
Sudo pip3 install openpyxl
为了将一个 excel 文件复制到另一个,我们首先打开源 excel 文件和目标 excel 文件。然后我们计算源excel文件中的总行数和列数,读取单个单元格值并将其存储在一个变量中,然后将该值写入目标excel文件中与源文件中单元格位置相似的单元格位置.保存目标文件。
程序 -
1) Import openpyxl library as xl.
2) Open the source excel file using the path in which it is located.
Note: The path should be a string and have double backslashes (\\) instead of single backslash (\). Eg: Path should be C:\\Users\\Desktop\\source.xlsx
Instead of C:\Users\Admin\Desktop\source.xlsx
3) Open the required worksheet to copy using the index of it. The index of worksheet ‘n’ is ‘n-1’. For example, the index of worksheet 1 is 0.
4) Open the destination excel file and the active worksheet in it.
5) Calculate the total number of rows and columns in source excel file.
6) Use two for loops (one for iterating through rows and another for iterating through columns of the excel file) to read the cell value in source file to a variable and then write it to a cell in destination file from that variable.
7) Save the destination file.
# importing openpyxl module
import openpyxl as xl;
# opening the source excel file
filename ="C:\\Users\\Admin\\Desktop\\trading.xlsx"
wb1 = xl.load_workbook(filename)
ws1 = wb1.worksheets[0]
# opening the destination excel file
filename1 ="C:\\Users\\Admin\\Desktop\\test.xlsx"
wb2 = xl.load_workbook(filename1)
ws2 = wb2.active
# calculate total number of rows and
# columns in source excel file
mr = ws1.max_row
mc = ws1.max_column
# copying the cell values from source
# excel file to destination excel file
for i in range (1, mr + 1):
for j in range (1, mc + 1):
# reading cell value from source excel file
c = ws1.cell(row = i, column = j)
# writing the read value to destination excel file
ws2.cell(row = i, column = j).value = c.value
# saving the destination excel file
wb2.save(str(filename1))
源文件:
输出:
在评论中写代码?请使用 ide.geeksforgeeks.org,生成链接并在此处分享链接。