系统:Windows 7 语言版本:Anaconda3-4.3.0.1-Windows-x86_64 编辑器:pycharm-community-2016.3.2
批量赋值
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")
print(current_address)
xl_app = win32com.client.gencache.EnsureDispatch("Excel.Application") # 若想引用常数的话使用此法调用Excel
xl_app.Visible = False # 是否显示Excel文件
wb = xl_app.Workbooks.Open(excel_address)
sht = wb.Worksheets(1)
sht.Name = "示例"# 批量赋值
list_1 = [1, 2, 3, 4, 5]
list_length = len(list_1)
sht.Range(sht.Cells(1, 1), sht.Cells(1, list_length)).Value = list_1list_2 = [6, 7, 8, 9, 10]
list_length = len(list_2)
sht.Range(sht.Cells(2, 1), sht.Cells(2, list_length)).Value = list_2wb.Save()
wb.Close()
代码截图
执行结果
清空单元格
在运行之前,先给单元格加点底色,效果如图
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")
print(current_address)
xl_app = win32com.client.gencache.EnsureDispatch("Excel.Application") # 若想引用常数的话使用此法调用Excel
xl_app.Visible = False # 是否显示Excel文件
wb = xl_app.Workbooks.Open(excel_address)
sht = wb.Worksheets(1)
sht.Name = "示例"
rng_1 = sht.Range(sht.Cells(2, 1), sht.Cells(2, 3))
rng_1.Value = ""
rng_1.Interior.Pattern = c.xlNone
rng_1.Interior.TintAndShade = 0
rng_1.Interior.PatternTintAndShade = 0
wb.Save()
wb.Close()
代码截图
执行结果
不但清空了数值,也清空了底色
rng_1.Interior.Pattern = c.xlNone
这一段代码其实是在Excel录制宏中录制的,只是在xlNone前加上c,这样就可以正常引用Excel中常数。