python办公自动化xlsx复制表格数据
时间: 2024-02-06 07:10:45 浏览: 67
可以使用 Python 的第三方库 `openpyxl` 来实现 Excel 文件的读写操作。
以下是一个简单的示例代码,演示如何打开一个 Excel 文件、复制表格数据并粘贴到另一个工作表中:
```python
import openpyxl
# 打开 Excel 文件
wb = openpyxl.load_workbook('example.xlsx')
# 选择要复制的工作表
source_sheet = wb['Sheet1']
# 创建一个新的工作表,并将复制的数据粘贴到新工作表中
target_sheet = wb.create_sheet('New Sheet')
for row in source_sheet.iter_rows():
for cell in row:
target_sheet[cell.coordinate].value = cell.value
# 保存修改后的 Excel 文件
wb.save('example_copy.xlsx')
```
在上面的代码中,`openpyxl.load_workbook()` 函数用于打开指定的 Excel 文件。`wb['Sheet1']` 用于选择要复制的工作表。`wb.create_sheet()` 用于创建一个新的工作表。`iter_rows()` 方法用于循环遍历表格中的每一行,`cell.coordinate` 属性用于获取单元格的坐标,`cell.value` 属性用于获取单元格中的值。
最后,调用 `wb.save()` 方法将修改后的 Excel 文件保存到磁盘中。
阅读全文
相关推荐
















