Change Cells Alignment and Keep Existing Formatting
Possible Usage Scenarios
Sometimes, you want to change the alignment of multiple cells but also want to keep existing formatting. Aspose.Cells allows you to do it using the StyleFlag.Alignments property. If you will set it true, changes in alignment will take place otherwise not. Please note, StyleFlag object is passed as a parameter to Range.applyStyle() method which actually applies the formatting to the range of cells.
Change Cells Alignment and Keep Existing Formatting
The following sample code loads the sample Excel file, creates the range and center aligns it horizontally and vertically and keeps the existing formatting intact. The following screenshot compares the sample Excel file and output Excel file and shows that all existing formatting of the cells is the same except that cells are now center aligned horizontally and vertically.
Sample Code
// 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); |