更改单元格对齐方式并保持现有格式
Contents
[
Hide
]
可能的使用场景
有时,您可能想要更改多个单元格的对齐方式,同时保留现有格式。使用Aspose.Cells可以实现这一点。如果将它设置为True,则对齐方面的更改将发生,否则不会。请注意,StyleFlag对象作为参数传递给Range.ApplyStyle()方法,该方法实际上将格式应用于一系列单元格。
更改单元格对齐方式并保留现有格式
以下示例代码加载了示例Excel文件(67338585.xlsx),创建范围并将其在水平和垂直方向上居中对齐,并保持现有格式不变。以下屏幕截图比较了示例Excel文件和输出Excel文件(67338586.xlsx),并显示了所有单元格的现有格式相同,只是单元格现在在水平和垂直方向上都居中对齐。
示例代码
This file contains 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
// 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. | |
Workbook wb = new Workbook(sourceDir + "sampleChangeCellsAlignmentAndKeepExistingFormatting.xlsx"); | |
// Access first worksheet. | |
Worksheet ws = wb.Worksheets[0]; | |
// Create cells range. | |
Range rng = ws.Cells.CreateRange("B2:D7"); | |
// Create style object. | |
Style st = wb.CreateStyle(); | |
// Set the horizontal and vertical alignment to center. | |
st.HorizontalAlignment = TextAlignmentType.Center; | |
st.VerticalAlignment = TextAlignmentType.Center; | |
// Create style flag object. | |
StyleFlag flag = new 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.ApplyStyle(st, flag); | |
// Save the workbook in XLSX format. | |
wb.Save(outputDir + "outputChangeCellsAlignmentAndKeepExistingFormatting.xlsx", SaveFormat.Xlsx); |