更改 Cells 对齐并保持现有格式
Contents
[
Hide
]
可能的使用场景
有时,您想要更改多个单元格的对齐方式,但又想保留现有格式。 Aspose.Cells 允许您使用StyleFlag.Alignments财产。如果你会设置它真的 否则不会发生对齐方式的变化。请注意,风格旗帜对象作为参数传递给范围.applyStyle() 方法,该方法实际上将格式应用于单元格区域。
更改 Cells 对齐并保持现有格式
下面的示例代码加载示例 Excel 文件创建范围并居中水平和垂直对齐并保持现有格式不变。以下屏幕截图比较了示例 Excel 文件和输出Excel文件并显示单元格的所有现有格式都是相同的,除了单元格现在水平和垂直居中对齐。
示例代码
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-Java | |
// Load sample Excel file containing cells with formatting. | |
Workbook wb = new Workbook(srcDir + "sampleChangeCellsAlignmentAndKeepExistingFormatting.xlsx"); | |
// Access first worksheet. | |
Worksheet ws = wb.getWorksheets().get(0); | |
// Create cells range. | |
Range rng = ws.getCells().createRange("B2:D7"); | |
// Create style object. | |
Style st = wb.createStyle(); | |
// Set the horizontal and vertical alignment to center. | |
st.setHorizontalAlignment(TextAlignmentType.CENTER); | |
st.setVerticalAlignment(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.setAlignments(true); | |
// Apply style to range of cells. | |
rng.applyStyle(st, flag); | |
// Save the workbook in XLSX format. | |
wb.save(outDir + "outputChangeCellsAlignmentAndKeepExistingFormatting.xlsx", SaveFormat.XLSX); |