更改单元格对齐方式并保持现有格式
Contents
[
Hide
]
可能的使用场景
有时,你想同时更改多个单元格的对齐方式,又希望保持已有格式。Aspose.Cells for Python via .NET允许你使用StyleFlag.alignments属性实现。如果将其设置为true,则对齐方式的更改会生效,否则不变。请注意,StyleFlag对象作为参数传递给Range.apply_style()方法,该方法实际应用格式到一范围单元格。
更改单元格对齐方式并保留现有格式
以下示例代码加载了示例Excel文件(67338585.xlsx),创建范围并将其在水平和垂直方向上居中对齐,并保持现有格式不变。以下屏幕截图比较了示例Excel文件和输出Excel文件(67338586.xlsx),并显示了所有单元格的现有格式相同,只是单元格现在在水平和垂直方向上都居中对齐。
示例代码
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from aspose.cells import SaveFormat, StyleFlag, TextAlignmentType, Workbook | |
# For complete examples and data files, please go to https:# github.com/aspose-cells/Aspose.Cells-for-.NET | |
# Load sample Excel file containing cells with formatting. | |
wb = Workbook(sourceDir + "sampleChangeCellsAlignmentAndKeepExistingFormatting.xlsx") | |
# Access first worksheet. | |
ws = wb.worksheets[0] | |
# Create cells range. | |
rng = ws.cells.create_range("B2:D7") | |
# Create style object. | |
st = wb.create_style() | |
# Set the horizontal and vertical alignment to center. | |
st.horizontal_alignment = TextAlignmentType.CENTER | |
st.vertical_alignment = TextAlignmentType.CENTER | |
# Create style flag object. | |
flag = StyleFlag() | |
# Set style flag alignments true. It is most crucial statement. | |
# Because if it will be false, no changes will take place. | |
flag.alignments = True | |
# Apply style to range of cells. | |
rng.apply_style(st, flag) | |
# Save the workbook in XLSX format. | |
wb.save(outputDir + "outputChangeCellsAlignmentAndKeepExistingFormatting.xlsx", SaveFormat.XLSX) |