Python-Excel-08- Copy Sheet

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

  1. Excel has a file copy worksheet .xlsx , which is the name of a worksheet examples
  2. Copy the example worksheet, a new worksheet name for the new copy
  3. In the new copy sheet B1 into a cell replication

Original table

7490971-5f37641d564bef79.png
1.png

After copying

7490971-726643cc5585afe4.png
2.png

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

7490971-7cecc2c1500391ce.png
3.png

Part 3: Interpretation of the code

  1. sht.Copy(After=sht), Copy a new table and its position on shtthe
  2. wb.ActiveSheet.Name = new_sht_name, Modify the name of the new worksheet
  3. sht_copy = wb.Worksheets(new_sht_name)Acquiring new worksheet object
  4. 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


7490971-89b1088ed19e2103.jpg
12x0.8.jpg

Reproduced in: https: //www.jianshu.com/p/d09304f9bd2b

Guess you like

Origin blog.csdn.net/weixin_33753845/article/details/91157320