单元格格式
Contents
[
Hide
]
格式化单元格或一系列单元格
如果要格式化单元格或一系列单元格,那么Aspose.Cells提供Style类。您可以使用此类完成单元格或一系列单元格的所有格式设置。使用IStyle类可以完成一些与格式设置相关的事项,如下所示
- 设置单元格的填充颜色
- 设置单元格的文本换行
- 设置单元格的边框,如顶部、左侧、底部和右侧边框等
- 设置字体颜色、字体大小、字体名称、删除线、粗体、斜体、下划线等
- 设置文本的水平或竖直对齐方式,右对齐、左对齐、顶部对齐、底部对齐、居中等
如果要设置单个单元格的样式,请使用Cell->SetStyle()方法,如果要设置一系列单元格的样式,请使用Range->ApplyStyle()方法。
示例代码
以下示例代码以各种方式格式化工作表的单元格C4,屏幕截图显示了通过代码生成的输出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
Aspose::Cells::Startup(); | |
//For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-C | |
//Path of input | |
U16String dirPath(u""); | |
//Path of output | |
U16String outPath(u""); | |
//Path of output excel file | |
U16String outputFormatCellOrRangeOfCells = outPath + "outputFormatCellOrRangeOfCells.xlsx"; | |
//Create a new workbook | |
Workbook wb; | |
//Get first worksheet which is created by default | |
Worksheet ws = wb.GetWorksheets().Get(0); | |
//Access cell C4 by cell name | |
Cell cell = ws.GetCells().Get(u"C4"); | |
//Add some text in cell | |
cell.PutValue((U16String)u"This is sample data."); | |
//Access the cell style | |
Style st = cell.GetStyle(); | |
//Fille the cell color to Yellow | |
st.SetPattern(BackgroundType::Solid); | |
st.SetForegroundColor(Color{ 0xff, 0xff, 0xff, 0 });//Yellow | |
//Set the text to wrapp | |
st.SetIsTextWrapped(true); | |
//Set the left and right border to Red | |
st.SetBorder(BorderType::LeftBorder, CellBorderType::Thick, Color{ 0xff, 0xff, 0, 0 });//Red | |
st.SetBorder(BorderType::RightBorder, CellBorderType::Thick, Color{ 0xff, 0xff, 0, 0 });//Red | |
//Set font color, font size, strike, bold, italic | |
st.GetFont().SetColor(Color{ 0xff, 0, 0, 0xff });//Blue | |
st.GetFont().SetSize(16); | |
st.GetFont().SetStrikeType(TextStrikeType::Single); | |
st.GetFont().SetIsBold(true); | |
st.GetFont().SetIsItalic(true); | |
//Set text horizontal and vertical alignment to center | |
st.SetHorizontalAlignment(TextAlignmentType::Center); | |
st.SetVerticalAlignment(TextAlignmentType::Center); | |
//Set the cell style | |
cell.SetStyle(st); | |
//Set the cell column width and row height | |
ws.GetCells().SetColumnWidth(cell.GetColumn(), 20); | |
ws.GetCells().SetRowHeight(cell.GetRow(), 70); | |
//Save the output excel file | |
wb.Save(outputFormatCellOrRangeOfCells); | |
Aspose::Cells::Cleanup(); |