Original micro-channel public number
System : Windows 7
language versions : Anaconda3-4.3.0.1-Windows-x86_64
Editor : pycharm-community-2016.3.2
- Python talk about this series of operations on Excel
- Today to talk about the use win32com module, copy the worksheet
- In this time we do a lot of duplication of work, the first to develop a template, follow directly copy the table, do the modifications can be personalized
Part 1: illustration
- Excel has a file copy worksheet .xlsx , which is the name of a worksheet examples
- Copy the example worksheet, a new worksheet name for the new copy
- In the new copy sheet B1 into a cell replication
Original table
After copying
Part 2: Code
import os
import win32com
from win32com.client import constants as c # 旨在直接使用VBA常数
current_address = os.path.abspath('.')
excel_address = os.path.join(current_address, "复制工作表.xlsx")
xl_app = win32com.client.gencache.EnsureDispatch("Excel.Application") # 若想引用常数的话使用此法调用Excel
xl_app.Visible = False # 是否显示Excel文件
wb = xl_app.Workbooks.Open(excel_address)
sht = wb.Worksheets("示例")
# 复制工作表
new_sht_name = "新复制"
sht.Copy(After=sht)
wb.ActiveSheet.Name = new_sht_name
sht_copy = wb.Worksheets(new_sht_name)
sht_copy.Range("B1").Value = "复制"
wb.Save()
wb.Close()
Code Screenshot
Part 3: Interpretation of the code
-
sht.Copy(After=sht)
, Copy a new table and its position onsht
the -
wb.ActiveSheet.Name = new_sht_name
, Modify the name of the new worksheet -
sht_copy = wb.Worksheets(new_sht_name)
Acquiring new worksheet object -
sht_copy.Range("B1").Value = "复制"
, Cell assignment
This article is an original work, please share circle of friends
Often by two-dimensional picture identification code, this public concern No.
Python elegant and handsome
Reproduced in: https: //www.jianshu.com/p/d09304f9bd2b