import math
from spire.doc import *
from spire.doc.common import *
# 创建Document对象
doc = Document()
# 添加一节
section = doc.AddSection()
# 创建一个表格
table = section.AddTable()
# 指定表格数据
header_data = ["商品名称", "单位", "数量", "单价"]
row_data = [ ["底板-1","件","20946","2.9"],
["定位板-2","张","38931","1.5"],
["整平模具-3","组","32478","1.1"],
["后壳FD1042-4","组","21162","0.6"],
["棍子-5","组","66517","1.2"]]
# 设置表格的行数和列数
table.ResetCells(len(row_data) + 1, len(header_data))
# 设置表格自适应窗口
table.AutoFit(AutoFitBehaviorType.AutoFitToWindow)
# 设置标题行
headerRow = table.Rows[0]
headerRow.IsHeader = True
headerRow.Height = 23
headerRow.RowFormat.BackColor = Color.get_Orange()
# 在标题行填充数据并设置文本格式
i = 0
while i < len(header_data):
headerRow.Cells[i].CellFormat.VerticalAlignment = VerticalAlignment.Middle
paragraph = headerRow.Cells[i].AddParagraph()
paragraph.Format.HorizontalAlignment = HorizontalAlignment.Center
txtRange = paragraph.AppendText(header_data[i])
txtRange.CharacterFormat.Bold = True
txtRange.CharacterFormat.FontSize = 12
i += 1
# 将数据填入其余各行并设置文本格式
r = 0
while r < len(row_data):
dataRow = table.Rows[r + 1]
dataRow.Height = 20
dataRow.HeightType = TableRowHeightType.Exactly
c = 0
while c < len(row_data[r]):
dataRow.Cells[c].CellFormat.VerticalAlignment = VerticalAlignment.Middle
paragraph = dataRow.Cells[c].AddParagraph()
paragraph.Format.HorizontalAlignment = HorizontalAlignment.Center
txtRange = paragraph.AppendText(row_data[r][c])
txtRange.CharacterFormat.FontSize = 11
c += 1
r += 1
# 设置交替行颜色
for j in range(1, table.Rows.Count):
if math.fmod(j, 2) == 0:
row2 = table.Rows[j]
for f in range(row2.Cells.Count):
row2.Cells[f].CellFormat.BackColor = Color.get_LightGray()
# 保存文件
doc.SaveToFile("Word表格.docx", FileFormat.Docx2016)
|