使用pycharm 把一个excel 的某几列数据 粘贴到另一个excel中某几列的最后
时间: 2023-11-05 07:04:34 浏览: 192
Pycharm简单使用教程(入门小结)
1. 打开PyCharm,创建一个新的Python文件。
2. 导入所需的模块:
```python
import openpyxl
```
3. 定义要复制的excel文件和sheet名称:
```python
source_file = "source.xlsx"
source_sheet_name = "Sheet1"
```
4. 打开源文件和工作表:
```python
source_workbook = openpyxl.load_workbook(source_file)
source_sheet = source_workbook[source_sheet_name]
```
5. 定义要复制的列的范围:
```python
source_column_start = 1
source_column_end = 3
```
6. 定义目标文件和sheet名称:
```python
target_file = "target.xlsx"
target_sheet_name = "Sheet1"
```
7. 打开目标文件和工作表:
```python
target_workbook = openpyxl.load_workbook(target_file)
target_sheet = target_workbook[target_sheet_name]
```
8. 定义要粘贴的列的范围:
```python
target_column_start = 4
target_column_end = 6
```
9. 循环遍历要复制的行和列,并将它们复制到目标文件中:
```python
for row in source_sheet.iter_rows(min_row=2, max_col=source_column_end):
target_row = []
for cell in row:
target_row.append(cell.value)
for i in range(target_column_start, target_column_end + 1):
target_sheet.cell(row=cell.row, column=i).value = target_row[i - target_column_start]
```
10. 保存目标文件:
```python
target_workbook.save(target_file)
```
完整代码如下:
```python
import openpyxl
source_file = "source.xlsx"
source_sheet_name = "Sheet1"
source_column_start = 1
source_column_end = 3
target_file = "target.xlsx"
target_sheet_name = "Sheet1"
target_column_start = 4
target_column_end = 6
source_workbook = openpyxl.load_workbook(source_file)
source_sheet = source_workbook[source_sheet_name]
target_workbook = openpyxl.load_workbook(target_file)
target_sheet = target_workbook[target_sheet_name]
for row in source_sheet.iter_rows(min_row=2, max_col=source_column_end):
target_row = []
for cell in row:
target_row.append(cell.value)
for i in range(target_column_start, target_column_end + 1):
target_sheet.cell(row=cell.row, column=i).value = target_row[i - target_column_start]
target_workbook.save(target_file)
```
阅读全文