[英]How to copy and paste existing sheet in existing workbook using python?
I've been searching for a way to do the following:我一直在寻找一种方法来执行以下操作:
Open an existing workbook that contains several worksheets, .xlsl
.打开包含多个工作表
.xlsl
的现有工作簿。
Create a new worksheet, and rename it.创建一个新的工作表,并重命名。
Copy data and formatting from an existing worksheet, named 'Template', and paste that data to the previously created worksheet.从名为“模板”的现有工作表复制数据和格式,然后将该数据粘贴到之前创建的工作表中。
Is there any way to do what I need?有什么办法可以做我需要的吗?
EDIT: This is the way how to do it:编辑:这是如何做到这一点的方式:
import openpyxl
from openpyxl.worksheet.copier import WorksheetCopy
workbook = openpyxl.load_workbook('input.xlsx')
template_worksheet = workbook.get_sheet_by_name(sheet_name)
new_worksheet = workbook.create_sheet('New_Sheet_Name')
instance = WorksheetCopy(template_worksheet, new_worksheet)
WorksheetCopy.copy_worksheet(instance)
workbook.save('output.xlsx')
You will have to use python package for this task, I recommend you use openpyxl
package.你将不得不使用 python 包来完成这个任务,我建议你使用
openpyxl
包。 Basic usage of the package can be found here.可以在此处找到该包的基本用法。
https://openpyxl.readthedocs.io/en/default/usage.html https://openpyxl.readthedocs.io/en/default/usage.html
You will basically read the excel and at the same time write a new excel, copying data row by row.您将基本上阅读 excel 并同时编写一个新的 excel,逐行复制数据。
I think You could use xlwings我认为你可以使用xlwings
Here You have description how to open Excel File : Opening Workbook在这里您描述了如何打开Excel 文件: 打开工作簿
and then siply use API to, copy one sheet and add as new one : Sheets-Api然后使用 API 复制一张工作表并添加为新工作表: Sheets-Api
Is there a particular need to use Python as your solution?是否特别需要使用 Python 作为您的解决方案? Using Visual Basic macros seems to be a better fit here.
在这里使用 Visual Basic 宏似乎更合适。 If it needs to fit in with a Python program consider building a macro in your Excel file, then calling that file from the Python script.
如果它需要适合 Python 程序,请考虑在 Excel 文件中构建宏,然后从 Python 脚本调用该文件。
Although this question is old, but hope the comment will still be useful to update newcomers.虽然这个问题很老了,但希望评论对更新新人仍然有用。
As mentioned by Falloutcoder, you can use the openpyxl module for the Excel task.正如 Falloutcoder 所提到的,您可以将 openpyxl 模块用于 Excel 任务。 For the data copy, you can use "for loop" and "ws2.cell(row=i,column=j).value=ws1.cell(row=i,column=j).value" functions to copy data from one sheet to another.
对于数据复制,您可以使用“for 循环”和“ws2.cell(row=i,column=j).value=ws1.cell(row=i,column=j).value”函数从一个复制数据表到另一个。 enter link description here
在此处输入链接描述
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.