For speed I am using data_only
and read_only
attributes when opening my workbooks. Also iter_rows()
is really fast, too.
@Oscar’s excellent answer needs some changes to support ReadOnlyWorksheet and EmptyCell
# Copy a sheet with style, format, layout, ect. from one Excel file to another Excel file
# Please add the ..path\+\file.. and ..sheet_name.. according to your desire.
import openpyxl
from copy import copy
def copy_sheet(source_sheet, target_sheet):
copy_cells(source_sheet, target_sheet) # copy all the cel values and styles
copy_sheet_attributes(source_sheet, target_sheet)
def copy_sheet_attributes(source_sheet, target_sheet):
if isinstance(source_sheet, openpyxl.worksheet._read_only.ReadOnlyWorksheet):
return
target_sheet.sheet_format = copy(source_sheet.sheet_format)
target_sheet.sheet_properties = copy(source_sheet.sheet_properties)
target_sheet.merged_cells = copy(source_sheet.merged_cells)
target_sheet.page_margins = copy(source_sheet.page_margins)
target_sheet.freeze_panes = copy(source_sheet.freeze_panes)
# set row dimensions
# So you cannot copy the row_dimensions attribute. Does not work (because of meta data in the attribute I think). So we copy every row's row_dimensions. That seems to work.
for rn in range(len(source_sheet.row_dimensions)):
target_sheet.row_dimensions[rn] = copy(source_sheet.row_dimensions[rn])
if source_sheet.sheet_format.defaultColWidth is None:
print('Unable to copy default column wide')
else:
target_sheet.sheet_format.defaultColWidth = copy(source_sheet.sheet_format.defaultColWidth)
# set specific column width and hidden property
# we cannot copy the entire column_dimensions attribute so we copy selected attributes
for key, value in source_sheet.column_dimensions.items():
target_sheet.column_dimensions[key].min = copy(source_sheet.column_dimensions[key].min) # Excel actually groups multiple columns under 1 key. Use the min max attribute to also group the columns in the targetSheet
target_sheet.column_dimensions[key].max = copy(source_sheet.column_dimensions[key].max) # https://stackoverflow.com/questions/36417278/openpyxl-can-not-read-consecutive-hidden-columns discussed the issue. Note that this is also the case for the width, not onl;y the hidden property
target_sheet.column_dimensions[key].width = copy(source_sheet.column_dimensions[key].width) # set width for every column
target_sheet.column_dimensions[key].hidden = copy(source_sheet.column_dimensions[key].hidden)
def copy_cells(source_sheet, target_sheet):
for r, row in enumerate(source_sheet.iter_rows()):
for c, cell in enumerate(row):
source_cell = cell
if isinstance(source_cell, openpyxl.cell.read_only.EmptyCell):
continue
target_cell = target_sheet.cell(column=c+1, row=r+1)
target_cell._value = source_cell._value
target_cell.data_type = source_cell.data_type
if source_cell.has_style:
target_cell.font = copy(source_cell.font)
target_cell.border = copy(source_cell.border)
target_cell.fill = copy(source_cell.fill)
target_cell.number_format = copy(source_cell.number_format)
target_cell.protection = copy(source_cell.protection)
target_cell.alignment = copy(source_cell.alignment)
if not isinstance(source_cell, openpyxl.cell.ReadOnlyCell) and source_cell.hyperlink:
target_cell._hyperlink = copy(source_cell.hyperlink)
if not isinstance(source_cell, openpyxl.cell.ReadOnlyCell) and source_cell.comment:
target_cell.comment = copy(source_cell.comment)
With a usage something like
wb = Workbook()
wb_source = load_workbook(filename, data_only=True, read_only=True)
for sheetname in wb_source.sheetnames:
source_sheet = wb_source[sheetname]
ws = wb.create_sheet("Orig_" + sheetname)
copy_sheet(source_sheet, ws)
wb.save(new_filename)
Solution 1
A Python-only solution using the openpyxl
package. Only data values will be copied.
import openpyxl as xl
path1 = 'C:\Users\Xukrao\Desktop\workbook1.xlsx'
path2 = 'C:\Users\Xukrao\Desktop\workbook2.xlsx'
wb1 = xl.load_workbook(filename=path1)
ws1 = wb1.worksheets[0]
wb2 = xl.load_workbook(filename=path2)
ws2 = wb2.create_sheet(ws1.title)
for row in ws1:
for cell in row:
ws2[cell.coordinate].value = cell.value
wb2.save(path2)
Solution 2
A solution that uses the pywin32
package to delegate the copying operation to an Excel application. Data values, formatting and everything else in the sheet is copied. Note: this solution will work only on a Windows machine that has MS Excel installed.
from win32com.client import Dispatch
path1 = 'C:\Users\Xukrao\Desktop\workbook1.xlsx'
path2 = 'C:\Users\Xukrao\Desktop\workbook2.xlsx'
xl = Dispatch("Excel.Application")
xl.Visible = True # You can remove this line if you don't want the Excel application to be visible
wb1 = xl.Workbooks.Open(Filename=path1)
wb2 = xl.Workbooks.Open(Filename=path2)
ws1 = wb1.Worksheets(1)
ws1.Copy(Before=wb2.Worksheets(1))
wb2.Close(SaveChanges=True)
xl.Quit()
Solution 3
A solution that uses the xlwings
package to delegate the copying operation to an Excel application. Xlwings is in essence a smart wrapper around (most, though not all) pywin32
/appscript
excel API functions. Data values, formatting and everything else in the sheet is copied. Note: this solution will work only on a Windows or Mac machine that has MS Excel installed.
import xlwings as xw
path1 = 'C:\Users\Xukrao\Desktop\workbook1.xlsx'
path2 = 'C:\Users\Xukrao\Desktop\workbook2.xlsx'
wb1 = xw.Book(path1)
wb2 = xw.Book(path2)
ws1 = wb1.sheets(1)
ws1.api.Copy(Before=wb2.sheets(1).api)
wb2.save()
wb2.app.quit()
Вопрос:
У меня есть строка с исходным файлом и другая строка с пути destfile, указывающие на книги Excel.
Я хочу взять первый лист исходного файла и скопировать его в качестве новой вкладки в файл destfile (неважно, где находится файл destfile), а затем сохранить его.
Не удалось найти простой способ в xlrd
или xlwt
или xlutils
сделать это. Я что-то пропустил?
Лучший ответ:
Содержание
- Решение 1
- Решение 2
- Решение 3
Решение 1
Решение только для Python с использованием пакета openpyxl
. Будут скопированы только значения данных.
import openpyxl as xl
path1 = 'C:\Users\Xukrao\Desktop\workbook1.xlsx'
path2 = 'C:\Users\Xukrao\Desktop\workbook2.xlsx'
wb1 = xl.load_workbook(filename=path1)
ws1 = wb1.worksheets[0]
wb2 = xl.load_workbook(filename=path2)
ws2 = wb2.create_sheet(ws1.title)
for row in ws1:
for cell in row:
ws2[cell.coordinate].value = cell.value
wb2.save(path2)
Решение 2
Решение, использующее пакет pywin32
для делегирования операции копирования приложению Excel. Значения данных, форматирование и все остальное в листе копируется. Примечание. Это решение будет работать только на компьютере с Windows, на котором установлен MS Excel.
from win32com.client import Dispatch
path1 = 'C:\Users\Xukrao\Desktop\workbook1.xlsx'
path2 = 'C:\Users\Xukrao\Desktop\workbook2.xlsx'
xl = Dispatch("Excel.Application")
xl.Visible = True # You can remove this line if you don't want the Excel application to be visible
wb1 = xl.Workbooks.Open(Filename=path1)
wb2 = xl.Workbooks.Open(Filename=path2)
ws1 = wb1.Worksheets(1)
ws1.Copy(Before=wb2.Worksheets(1))
wb2.Close(SaveChanges=True)
xl.Quit()
Решение 3
Решение, использующее пакет xlwings
для делегирования операции копирования приложению Excel. По сути, Xlwings – это умная оболочка (большинство, хотя и не все) функций API Excel pywin32
/appscript
. Значения данных, форматирование и все остальное в листе копируется. Примечание. Это решение будет работать только на компьютере с Windows или Mac, на котором установлен MS Excel.
import xlwings as xw
path1 = 'C:\Users\Xukrao\Desktop\workbook1.xlsx'
path2 = 'C:\Users\Xukrao\Desktop\workbook2.xlsx'
wb1 = xw.Book(path1)
wb2 = xw.Book(path2)
ws1 = wb1.sheets(1)
ws1.api.Copy(Before=wb2.sheets(1).api)
wb2.save()
wb2.app.quit()
Ответ №1
Это может помочь, если вы не против использования Pandas
import pandas as pd
#change xxx with the sheet name that includes the data
data = pd.read_excel(sourcefile, sheet_name="xxx")
#save it to the 'new_tab' in destfile
data.to_excel(destfile, sheet_name='new_tab')
Надеюсь, что это поможет
Ответ №2
Вы также можете попробовать xlwings.
import xlwings as xw
wb = xw.Book(r'C:pathtofile.xlsx')
sht = wb.sheets['Sheet1']
new_wb = xw.Book(r'C:new_pathtofile.xlsx')
new_wb.sheets['name'] = sht
In this article, I will tell you how to use the python openpyxl library to copy one excel sheet data to another excel sheet, the two excel sheets can be in the same excel file or different excel file. If you do not know the openpyxl library, you can read the article How To Create / Load Excel File In Python Using Openpyxl first.
1. Copy Excel Sheet Data Example.
Below are the example project files. The python source file is copy_excel_sheet.py. It contains 5 methods, and the source excel file is test_excel.xlsx.
$ tree ./ ./ ├── __init__.py ├── copy_excel_sheet.py ├── create_load_excel_file.py ├── data │ ├── excel-example.xlsx │ ├── financial_sample.xlsx │ ├── financial_sample_freeze_1.xlsx │ ├── reviews_sample.xlsx │ ├── test_default_excel.xlsx │ ├── test_excel.xlsx │ ├── test_excel_1.xlsx │ ├── test_excel_2.xls │ └── ~$financial_sample.xlsx └── freeze_split_excel_pane.py
The copy_excel_sheet.py file contains the below methods.
- if_file_exist(file_path).
- if_excel_sheet_exist(work_book, work_sheet_name).
- copy_excel_sheet_in_same_file(file_path, source_sheet_name, target_sheet_name).
- copy_excel_sheet_in_same_file_by_copy_worksheet(file_path, source_sheet_name, target_sheet_name).
- copy_excel_sheet_in_different_file(source_file_path, source_sheet_name, target_file_path).
Below is the original data of the test_excel.xlsx file.
Below is the excel file after executing the copy_excel_sheet_in_same_file method, it adds a new excel sheet User Account New in test_excel.xlsx.
Below is the excel file after executing the copy_excel_sheet_in_same_file_by_copy_worksheet method, it is similar to the above, but it cloned the entire sheet even the sheet tab color to the new excel sheet.
If you execute the copy_excel_sheet_in_different_file method, it will create a new excel file test_excel_1.xlsx, and there is an excel sheet with the name User Account in the test_excel_1.xlsx.
2. Copy Excel Sheet Data Example Source Code.
''' @author: zhaosong ''' import openpyxl, os from openpyxl import Workbook from openpyxl import load_workbook ''' Check whether the file exist or not. file_path : the input file path with name. Return True if the file exist otherwise return False. ''' def if_file_exist(file_path): if os.path.exists(file_path): return True else: return False ''' Check whether the excel file contain the excel sheet. work_book : openpyxl.Workbook instance. work_sheet_name : excel sheet name. Return True if the excel file contain the excel sheet otherwise return False. ''' def if_excel_sheet_exist(work_book, work_sheet_name): sheet_names_list = work_book.sheetnames for sheet_name in sheet_names_list: if sheet_name == work_sheet_name: return True else: return False ''' Copy one excel sheet data to another excel sheet in same excel file. file_path : Excel file path. source_sheet_name : the source excel sheet name that will be copied. target_sheet_name : the target excel sheet name. ''' def copy_excel_sheet_in_same_file(file_path, source_sheet_name, target_sheet_name): if if_file_exist(file_path): print("File ", file_path, " exist.") # load the excel file return Workbook object. work_book = load_workbook(file_path) if if_excel_sheet_exist(work_book, source_sheet_name): print("Source excel sheet ", source_sheet_name, " exist.") # get source Worksheet object. source_work_sheet = work_book[source_sheet_name] # initialise the target_work_sheet to None. target_work_sheet = None # if target excel sheet exist in the excel file. if if_excel_sheet_exist(work_book, target_sheet_name): # assign the target Worksheet. target_work_sheet = work_book[target_sheet_name] else: # create a new Worksheet object. target_work_sheet = work_book.create_sheet(target_sheet_name) # loop the source excel sheet rows. row_number = 1 for row in source_work_sheet.iter_rows(): # loop the cell in the row. cell_column_number = 1 for cell in row: # create a cell in target work sheet. target_cell = target_work_sheet.cell(row = row_number, column = cell_column_number, value = cell.value) cell_column_number += 1 row_number += 1 # save the excel file. work_book.save(file_path) print("Excel sheet has be copied. ") else: print("Source excel sheet ", source_sheet_name, " do not exist.") else: print("File ", file_path, " do not exist.") ''' Clone entire excel sheet in same excel file use Workbook object's copy_worksheet method. ''' def copy_excel_sheet_in_same_file_by_copy_worksheet(file_path, source_sheet_name, target_sheet_name): if if_file_exist(file_path): print("File ", file_path, " exist.") # load the excel file return Workbook object. work_book = load_workbook(file_path) if if_excel_sheet_exist(work_book, source_sheet_name): print("Source excel sheet ", source_sheet_name, " exist.") source_sheet = work_book[source_sheet_name] # invoke copy_worksheet method to clone source sheet. target_sheet = work_book.copy_worksheet(source_sheet) target_sheet.title = target_sheet_name # save the excel file. work_book.save(file_path) print("Excel sheet has be copied. ") else: print("Source excel sheet ", source_sheet_name, " do not exist.") else: print("File ", file_path, " do not exist.") ''' Copy excel sheet data from one excel file to another excel file. source_file_path : source excel file path with name. source_sheet_name : source excel sheet name. target_file_path : target excel file path with name. ''' def copy_excel_sheet_in_different_file(source_file_path, source_sheet_name, target_file_path): if if_file_exist(source_file_path): print("File ", source_file_path, " exist.") # load Workbook object source excel file. source_work_book = load_workbook(source_file_path) if if_excel_sheet_exist(source_work_book, source_sheet_name): print("Source excel sheet ", source_sheet_name, " exist.") # get source Worksheet object. source_work_sheet = source_work_book[source_sheet_name] target_work_book = None target_work_sheet = None target_sheet_name = source_sheet_name # if target excel file exist then load it. if if_file_exist(target_file_path): target_work_book = load_workbook(target_file_path) # otherwise create a new Workbook object. else: target_work_book = Workbook() # if target excel sheet exist in target excel file the return it. if if_excel_sheet_exist(target_work_book, target_sheet_name): target_work_sheet = target_work_book[target_sheet_name] # otherwise create a new Worksheet object. else: target_work_sheet = target_work_book.create_sheet(target_sheet_name) # loop in the source excel sheet rows. row_number = 1 for row in source_work_sheet.iter_rows(): # loop in the row cells. cell_column_number = 1 for cell in row: # create a target excel cell in target excel sheet. target_cell = target_work_sheet.cell(row = row_number, column = cell_column_number, value = cell.value) cell_column_number += 1 row_number += 1 # save the target excel file. target_work_book.save(target_file_path) print("Excel sheet has be copied. ") else: print("Source excel sheet ", source_sheet_name, " do not exist.") else: print("File ", source_file_path, " do not exist.") if __name__ == '__main__': source_file_path = './test_excel.xlsx' source_sheet_name = 'User Account' target_sheet_name = 'User Account New' copy_excel_sheet_in_same_file_by_copy_worksheet(source_file_path, source_sheet_name, target_sheet_name) #copy_excel_sheet_in_same_file(source_file_path, source_sheet_name, target_sheet_name) #target_file_path = './test_excel_1.xlsx' #copy_excel_sheet_in_different_file(source_file_path, source_sheet_name, target_file_path)
Reference
- How To Create / Load Excel File In Python Using Openpyxl
Improve Article
Save Article
Like Article
Improve Article
Save Article
Like Article
In this article, we will learn how to copy data from one excel sheet to destination excel workbook using openpyxl module in Python.
For working with excel files, we require openpyxl
, which is a Python library that is used for reading, writing and modifying excel (with extension xlsx/xlsm/xltx/xltm) files. It can be installed using the following command:
Sudo pip3 install openpyxl
For copying one excel file to another, we first open both the source and destination excel files. Then we calculate the total number of rows and columns in the source excel file and read a single cell value and store it in a variable and then write that value to the destination excel file at a cell position similar to that of the cell in source file. The destination file is saved.
Procedure –
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 ofC:UsersAdminDesktopsource.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.
import
openpyxl as xl;
filename
=
"C:\Users\Admin\Desktop\trading.xlsx"
wb1
=
xl.load_workbook(filename)
ws1
=
wb1.worksheets[
0
]
filename1
=
"C:\Users\Admin\Desktop\test.xlsx"
wb2
=
xl.load_workbook(filename1)
ws2
=
wb2.active
mr
=
ws1.max_row
mc
=
ws1.max_column
for
i
in
range
(
1
, mr
+
1
):
for
j
in
range
(
1
, mc
+
1
):
c
=
ws1.cell(row
=
i, column
=
j)
ws2.cell(row
=
i, column
=
j).value
=
c.value
wb2.save(
str
(filename1))
Source File:
Output:
Like Article
Save Article
OpenPyXl is a Python open library that allows you to read and write Microsoft Excel files. Specifically, the ‘*.xlsx’ file extension. It helps you to create programs to create and modify files and automate your processes in excel.
NOTE: This post requires that you have some knowledge of Python and the OpenPyXl library. The library also needs to be installed for you to use.
Quite often, I find that I have to work with ranges of data that I need to either copy and paste into a new file or files, or copy > modify > paste into files.
The OpenPyXl library allows you to look at every cell of a file and either copy it or modify it by using the openpyxl.worksheet.Worksheet.
cell()
method. This method allows you to access each cell by the row and column as a numerical value.
Note! Unlike everything else in coding, rows and columns start with one(1) and not zero(0).
To select whole ranges of our data we need to iterate through it by both row and column and then store that data in a list to be pasted to the new file, spreadsheet or location that we desire.
The following example will take you through the process. For your own data you will need to modify the file, sheet and range locations. Everything else should be good to go.
You can find the whole code at the end of the post.
Why does your MS Excel look weird?
To be honest my screenshots of the ‘.xlsx files will be in Libreoffice. But this simple example will be able to load without issue in MS Excel.
The Example
Source Data
The source data for this example is a very simplified version of grade data that I work with day-to-day. The goal of our program is to simply copy the Section 12 results into a new file. The file for this spreadsheet is called: GradeSample.xlsx
. I have put it in the same folder as my Python program.
Receiving File
For the purpose of this example, we have a file that we want to save this data into: Section12Grades.xlsx
. We could just as easily use a template and save the file under a different name – for example, template.xlsx
could save as sec12Grade.xlsx
. This could be useful if I wanted to save a file for each section.
The receiving file looks like this:
Loading the Source Data and Receiving File
Okay, let’s get started with the program. First, we need to load both the source data and the receiving file.
#! Python 3 # — Copy and Paste Ranges using OpenPyXl library import openpyxl #Prepare the spreadsheets to copy from and paste too. #File to be copied wb = openpyxl.load_workbook(«GradeSample.xlsx») #Add file name sheet = wb.get_sheet_by_name(«Grades») #Add Sheet name #File to be pasted into template = openpyxl.load_workbook(«Section12Grades.xlsx») #Add file name temp_sheet = template.get_sheet_by_name(«Sheet1») #Add Sheet name |
We import he OpenPyXl library first.
Next, we’ll open the source data with wb = openpyxl.load_workbook("GradeSample.xlsx")
. Once we have loaded the workbook we need to tell Python which sheet tab we want it to work in. We do this by calling the workbook (wb
) and then get the sheet by its name: sheet = wb.get_sheet_by_name("Grades")
We repeat this step with the receiving data file that we want to paste our Section 12 grades into.
Copying the Section 12 data
Looking at the section 12 data, we want Python to be able to copy from column A2 to D14. the OpenPyXl .cell()
method takes a number which is much easier to iterate, rather than the column letters. So let’s look at that range again:
- From: A2 is now column = 1 and row = 2
- To: D14 in now column = 4 and row = 14
Once we access this data, we need somewhere to store it before we paste it into the new file. We will use a nested list for this.
#Copy range of cells as a nested list #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 |
In line 3 we create our function copyRange. It contains 5 arguments that we could add with our information as follows:
- startCol = 1
- startRow = 2
- endCol = 4
- endRow = 14
- sheet = sheet ( The name of the sheet variable we are copying the data from which is
GradeSample.xlsx
sheetGrades
)
In line 4 we create an empty list called rangeSelected
this list will have data from every row we have selected.
Line 5 starts the for
loop through each row. Each row contains data in each column so we create an empty list (rowSelected
) here in preparation to add the column data to in the next for
loop (Line 6).
Line 6 loops through each item in each column of the selected row. Line 7 then adds the data from each column to the rowSelected
lists.
Once it finishes this loop, it adds the data from the rowSelected
lists into the rangeSelected
lists. It then moves down to the next row and repeats the process continuing through the rows until the loop meets its end at row 14.
Finally the copyRange
function returns the rangeSelected
list to be used at our discretion.
Pasting the selected data
Now we have a nested list of all the rows and the information in the columns we require from those rows.
We will use that list add it to our Section12Grades.xlsx
in Sheet1
.
We want to add the data starting at row 3 this time because we have a title on row 1 and column headers on row 2.
We will be up for two more for loops to do this.
Let’s take a look:
#Paste range #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 |
Line 3 starts our pasteRange
function and contains the following arguments:
- startCol = 1
- startRow = 3 (because we want to paste the data 1 row down.)
- endCol = 4
- endRow = 15 (because we want to paste the data 1 row down.)
- sheetReceiving =
temp_sheet
(This is the variable forSection12Grades.xlsx
with the sheet name,Sheet1
. - copiedData =
rangeSelected
( The returned list from yourcopyRange
function)
Line 5 creates a count number variable starting with zero(0) so we can start looking through our copiedData
lists by rows from the beginning.
Line 6 begins the row loop like the copyRange
function.
Line 7 adds another count number variable so we can loop through our copiedData
list by columns.
Line 8 begins the column loop.
Line 9 adds the copiedData
cell-by-cell to the new file. It does not save it here but holds it in memory to be saved to the file we choose in the future.
Finally, we add 1 to each of the counters so we can move onto the next cell.
Running a Copy and Paste as a function
We are now going to create a function to copy the data using the copyRange
function and paste the data using the pasteRange
function and then we will save the Section12Grades.xlsx
file contained in the variable, template
.
This is how it will look:
def createData(): print(«Processing…») selectedRange = copyRange(1,2,4,14,sheet) pastingRange = pasteRange(1,3,4,15,temp_sheet,selectedRange) template.save(«Section12Grades.xlsx») print(«Range copied and pasted!») |
Line 1 creates the function and then line 3 runs the copyRange
process with the arguments we need.
Note! After line 3 you could call a function to manipulate the data or add styling here before you paste it.
Line 4 then runs the pasteRange
function with the arguments we need.
Line 5 then saves the pasted data in the same file that we used in our memory. You could equally save the file with a different name and this will create a brand new file with the pasted data in it.
That’s it! Done.
Run the program
Now it’s time to run the program. Save the file and hit run (F5).
In the Python Shell run the program and then enter:
Your result will look like this:
>>> go = createData() Processing... Range copied and pasted! >>> |
Not too impressive, right?
Go into the folder and open your Section12Grades.xlsx spreadsheet.
It should now look like this:
The full OpenPyXl copy and paste range code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 |
#! Python 3 # — Copy and Paste Ranges using OpenPyXl library import openpyxl #Prepare the spreadsheets to copy from and paste too. #File to be copied wb = openpyxl.load_workbook(«foo.xlsx») #Add file name sheet = wb.get_sheet_by_name(«foo») #Add Sheet name #File to be pasted into template = openpyxl.load_workbook(«foo2.xlsx») #Add file name temp_sheet = template.get_sheet_by_name(«foo2») #Add Sheet name #Copy range of cells as a nested list #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 range #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(1,2,4,14,sheet) #Change the 4 number values pastingRange = pasteRange(1,3,4,15,temp_sheet,selectedRange) #Change the 4 number values #You can save the template as another file to create a new file here too.s template.save(«foo.xlsx») print(«Range copied and pasted!») |
Edit: 18 Nov 2018
From OpenPyXl version 2.5 onward, you might find that you get a Depreciation warning for:
sheet = wb.get_sheet_by_name("foo") #Add Sheet name
temp_sheet = template.get_sheet_by_name("foo2") #Add Sheet name
OpenPyXl 2.5 now provides the sheet names in a convenient list:
sheet = wb["foo"]#Add Sheet name
temp_sheet = template["foo2"]#Add Sheet name
Her is the updated code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 |
#! Python 3 # — Copy and Paste Ranges using OpenPyXl library import openpyxl #Prepare the spreadsheets to copy from and paste too. #File to be copied wb = openpyxl.load_workbook(«foo.xlsx») #Add file name sheet = wb[«foo»] #Add Sheet name #File to be pasted into template = openpyxl.load_workbook(«foo2.xlsx») #Add file name temp_sheet = template[«foo2»] #Add Sheet name #Copy range of cells as a nested list #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 range #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(1,2,4,14,sheet) #Change the 4 number values pastingRange = pasteRange(1,3,4,15,temp_sheet,selectedRange) #Change the 4 number values #You can save the template as another file to create a new file here too.s template.save(«foo.xlsx») print(«Range copied and pasted!») |
Big thanks to WY in the comments for reminding me to update this.
Want to learn how to automate your daily admin at work with Python? Udemy has some great Python automation courses that will help you learn how to automate your tasks so you can focus on what really matters.
Got a more specific problem you need help with, but don’t have the time to develop the skills? Fiverr’s your best bet to find a skilled professional to solve your problem quickly and cheaply. *
*The above affiliate links have been carefully researched to get you to what you specifically need. If you decide to click on one of these links it will cost you just the same as going to the site. If you decide to sign up, I just get a little pocket money to help pay for the costs of running this website.
3 ответа
Решение 1
Решение на основе Python с использованием пакета openpyxl
. Будут скопированы только значения данных.
import openpyxl as xl
path1 = 'C:\Users\Xukrao\Desktop\workbook1.xlsx'
path2 = 'C:\Users\Xukrao\Desktop\workbook2.xlsx'
wb1 = xl.load_workbook(filename=path1)
ws1 = wb1.worksheets[0]
wb2 = xl.load_workbook(filename=path2)
ws2 = wb2.create_sheet(ws1.title)
for row in ws1:
for cell in row:
ws2[cell.coordinate].value = cell.value
wb2.save(path2)
Решение 2
Решение с использованием приложения Excel для фактического копирования. Скопированы значения данных, форматирование и все остальное на листе.
from win32com.client import Dispatch
path1 = 'C:\Users\Xukrao\Desktop\workbook1.xlsx'
path2 = 'C:\Users\Xukrao\Desktop\workbook2.xlsx'
xl = Dispatch("Excel.Application")
xl.Visible = True # You can remove this line if you don't want the Excel application to be visible
wb1 = xl.Workbooks.Open(Filename=path1)
wb2 = xl.Workbooks.Open(Filename=path2)
ws1 = wb1.Worksheets(1)
ws1.Copy(Before=wb2.Worksheets(1))
wb2.Close(SaveChanges=True)
xl.Quit()
Xukrao
16 июнь 2017, в 20:01
Поделиться
Это может помочь, если вы не против использования Pandas
import pandas as pd
#change xxx with the sheet name that includes the data
data = pd.read_excel(sourcefile, sheet_name="xxx")
#save it to the 'new_tab' in destfile
data.to_excel(destfile, sheet_name='new_tab')
Надеюсь, что это поможет
Bubble Bubble Bubble Gut
16 июнь 2017, в 17:34
Поделиться
Вы также можете попробовать xlwings.
import xlwings as xl
wb = xw.Book(r'C:pathtofile.xlsx')
sht = wb.sheets['Sheet1']
new_wb = xw.Book(r'C:new_pathtofile.xlsx')
new_wb.sheets['name'] = sht
Josh Herzberg
16 июнь 2017, в 16:59
Поделиться
Ещё вопросы
- 0Попытка использовать URLRequestInfo :: SetStreamToFile и URLResponseInfo :: GetBodyAsFileRef
- 1Visual Studio заявляет, что существует неоднозначный вызов, когда существует только один метод с заданным именем
- 1Изображение, снятое с камеры, отображается в ImageView всегда горизонтально Android
- 1В чем разница между torch.Tensor () и torch.empty () в pytorch?
- 0Как найти ключевое слово в строке не между специальными тегами?
- 1Apache Camel: отказ от сплит-процессоров после завершения
- 0Подождите, пока SSH туннель, прежде чем продолжить сценарий
- 0функция JavaScript не работает в Firefox
- 0Ошибка: # 200 Пользователь не авторизовал приложение для выполнения этого действия
- 1Повторное использование лямбда-выражения
- 0ВНУТРЕННЯЯ СОЕДИНИТЕ НЕСКОЛЬКО КОЛОНН С ОДНОЙ СТОЛОМ MYSQL
- 0E_NOTICE: сообщить только неопределенные переменные
- 0получить значение из обратного вызова JSON
- 1TelephonyManager.getDeviceId (0) возвращает разные результаты
- 1Firefox не будет печатать, если я не установлю точку останова?
- 1Всплывающее окно запроса HTTP POST
- 1Ошибка значения размерности нейронной сети Keras Train: ожидается, что она будет иметь 2 измерения, но получит массив с формой (32, 1, 4)
- 0Ошибка в форме редактирования; Codeigniter
- 0Как сделать так, чтобы класс оставался активным, когда stop () отменяет анимацию?
- 0Как определить, использует ли пользователь IE, и сообщить им, что сайт не поддерживает IE?
- 0Возведение в квадрат значений в векторе
- 0Laravel PHP: загрузка изображения с большим размером файла приводит к тому, что getClientOriginalName () становится null
- 0Итераторы произвольного доступа — делает vector.end () — vector.begin () = vector.size () в C ++;
- 1Как экспортировать n числовых столбцов для PDF в Java?
- 0Я не могу получить свой связанный список для работы
- 0Код Dreamweaver отображается на странице дизайна, но не в режиме реального времени в браузере
- 0Как добавить / обновить ссылку на строку запроса до конца существующего URL
- 0Двусторонняя сортировка / несортировка с помощью перетаскивания с помощью пользовательского интерфейса JQuery
- 1Обещание не разрешает истину или ложь
- 1Как сделать POST-запрос при показе localhost с помощью localtunnel
- 0JQuery JSON получение всех частей объекта
- 0Поиск в angular.js по id
- 0Удалить элементы диапазона в векторе в C ++
- 1Java jmxremote не открывает порт
- 0Как я могу отправить динамические данные в файле начальной загрузки для электронной почты в Zend Framework
- 0Преобразование результата SELECT с помощью DISTINCT в функцию DELETE в MySQL
- 1получить данные PCM из mp3 файла в Android
- 0новая реликвия с несколькими приложениями и несколькими учетными записями на одном сервере
- 1динамически меняющаяся коробка с картинками
- 0Обработка Windows Setevent
- 0MySQL InnoDB в catch-22 в MAMP
- 1Android-галерея LinearLayouts
- 1Tensorflow tf.train.Saver не сохраняет все переменные
- 1Плагин Wildfly Maven не использует xa-datasource
- 1Java: есть сортировка слиянием O (N ^ 2) или O (N Log (N))
- 1Различные косые черты в путях веб-приложений
- 0Как я могу использовать лямбда-выражения для вызова метода для каждого элемента в коллекции?
- 1Поток документов с несколькими столбцами-WPF
- 1Невозможно определить тип SQL для … при создании таблиц с LinQ
- 0Сделайте эту функцию jQuery динамической