python中可以通过为Excel赋空值来清空单元格。
示例:
单元格如下:
清空单元格代码如下:
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()
执行结果:
更多Python知识请关注Python视频教程栏目。