Форматировать ячейки

Введение

Как форматировать ячейки с помощью методов GetStyle и SetStyle

Применить различные виды стилей форматирования на ячейки для установки цветов фона или переднего плана, границ, шрифтов, горизонтальных и вертикальных выравниваний, уровня отступа, направления текста, угла поворота и многое другое.

Как использовать методы GetStyle и SetStyle

Если разработчикам нужно применить различные стили форматирования к различным ячейкам, то лучше получить Style ячейки с помощью метода Cell.GetStyle, указать атрибуты стиля, а затем применить форматирование с помощью метода Cell.SetStyle. Приведен пример, демонстрирующий этот подход к применению различного форматирования к ячейке.

// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
// Create directory if it is not already present.
bool IsExists = System.IO.Directory.Exists(dataDir);
if (!IsExists)
System.IO.Directory.CreateDirectory(dataDir);
// Instantiating a Workbook object
Workbook workbook = new Workbook();
// Obtaining the reference of the first worksheet
Worksheet worksheet = workbook.Worksheets[0];
// Accessing the "A1" cell from the worksheet
Cell cell = worksheet.Cells["A1"];
// Adding some value to the "A1" cell
cell.PutValue("Hello Aspose!");
// Defining a Style object
Aspose.Cells.Style style;
// Get the style from A1 cell
style = cell.GetStyle();
// Setting the vertical alignment
style.VerticalAlignment = TextAlignmentType.Center;
// Setting the horizontal alignment
style.HorizontalAlignment = TextAlignmentType.Center;
// Setting the font color of the text
style.Font.Color = Color.Green;
// Setting to shrink according to the text contained in it
style.ShrinkToFit = true;
// Setting the bottom border color to red
style.Borders[BorderType.BottomBorder].Color = Color.Red;
// Setting the bottom border type to medium
style.Borders[BorderType.BottomBorder].LineStyle = CellBorderType.Medium;
// Applying the style to A1 cell
cell.SetStyle(style);
// Saving the Excel file
workbook.Save(dataDir + "book1.out.xls");

Как использовать объект стиля для форматирования различных ячеек

Если разработчикам нужно применить одинаковый стиль форматирования к различным ячейкам, то они могут использовать Style объект. Пожалуйста, выполните следующие шаги для использования объекта Style:

  1. Добавьте объект Style, вызвав метод CreateStyle класса Workbook
  2. Получите только что добавленный объект Style
  3. Установите желаемые свойства/атрибуты объекта Style, чтобы применить желаемые настройки форматирования
  4. Присвойте настроенный объект Style вашим желаемым ячейкам

Этот подход может значительно повысить эффективность ваших приложений и сэкономить память.

// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
// Create directory if it is not already present.
bool IsExists = System.IO.Directory.Exists(dataDir);
if (!IsExists)
System.IO.Directory.CreateDirectory(dataDir);
// Instantiating a Workbook object
Workbook workbook = new Workbook();
// Adding a new worksheet to the Excel object
int i = workbook.Worksheets.Add();
// Obtaining the reference of the first worksheet by passing its sheet index
Worksheet worksheet = workbook.Worksheets[i];
// Accessing the "A1" cell from the worksheet
Cell cell = worksheet.Cells["A1"];
// Adding some value to the "A1" cell
cell.PutValue("Hello Aspose!");
// Adding a new Style
Style style = workbook.CreateStyle();
// Setting the vertical alignment of the text in the "A1" cell
style.VerticalAlignment = TextAlignmentType.Center;
// Setting the horizontal alignment of the text in the "A1" cell
style.HorizontalAlignment = TextAlignmentType.Center;
// Setting the font color of the text in the "A1" cell
style.Font.Color = Color.Green;
// Shrinking the text to fit in the cell
style.ShrinkToFit = true;
// Setting the bottom border color of the cell to red
style.Borders[BorderType.BottomBorder].Color = Color.Red;
// Setting the bottom border type of the cell to medium
style.Borders[BorderType.BottomBorder].LineStyle = CellBorderType.Medium;
// Assigning the Style object to the "A1" cell
cell.SetStyle(style);
// Apply the same style to some other cells
worksheet.Cells["B1"].SetStyle(style);
worksheet.Cells["C1"].SetStyle(style);
worksheet.Cells["D1"].SetStyle(style);
// Saving the Excel file
workbook.Save(dataDir + "book1.out.xls");

Как использовать предопределенные стили Microsoft Excel 2007

Если вам необходимо применить различные стили форматирования для Microsoft Excel 2007, примените стили с использованием API Aspose.Cells. Приведен пример, демонстрирующий этот подход к применению предопределенного стиля к ячейке.

// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
// Create directory if it is not already present.
bool IsExists = System.IO.Directory.Exists(dataDir);
if (!IsExists)
System.IO.Directory.CreateDirectory(dataDir);
// Instantiate a new Workbook.
Workbook workbook = new Workbook();
// Create a style object .
Style style = workbook.CreateStyle();
// Input a value to A1 cell.
workbook.Worksheets[0].Cells["A1"].PutValue("Test");
// Apply the style to the cell.
workbook.Worksheets[0].Cells["A1"].SetStyle(style);
// Save the Excel 2007 file.
workbook.Save(dataDir + "book1.out.xlsx");

Как форматировать выбранные символы в ячейке

Работа со настройками шрифта объясняет, как форматировать текст в ячейках, но это объясняет только, как форматировать весь содержимое ячейки. Что, если вы хотите отформатировать только выбранные символы?

Aspose.Cells также поддерживает эту функцию. В этой теме объясняется, как использовать эту функцию эффективно.

Как форматировать выбранные символы

Aspose.Cells предоставляет класс, Workbook который представляет файл Microsoft Excel. Класс Workbook содержит коллекцию Worksheets, которая позволяет получить доступ к каждому листу в файле Excel. Лист представлен классом Worksheet. Класс Worksheet обеспечивает коллекцию Cells. Каждый элемент в коллекции Cells представляет объект класса Cell.

Класс Cell предоставляет метод Characters, который принимает следующие параметры для выбора диапазона символов внутри ячейки:

  • Индекс начала, индекс символа, с которого начинается выбор.
  • Количество символов, количество выбираемых символов.

Метод Characters возвращает экземпляр класса FontSetting, который позволяет разработчикам форматировать символы таким же образом, как они бы это сделали с ячейкой, как показано ниже в примере кода. В выходном файле в ячейке A1 слово ‘Visit’ будет отформатировано шрифтом по умолчанию, но ‘Aspose!’ будет жирным и синим.

// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
// Create directory if it is not already present.
bool IsExists = System.IO.Directory.Exists(dataDir);
if (!IsExists)
System.IO.Directory.CreateDirectory(dataDir);
// Instantiating a Workbook object
Workbook workbook = new Workbook();
// Obtaining the reference of the first(default) worksheet by passing its sheet index
Worksheet worksheet = workbook.Worksheets[0];
// Accessing the "A1" cell from the worksheet
Cell cell = worksheet.Cells["A1"];
// Adding some value to the "A1" cell
cell.PutValue("Visit Aspose!");
// Setting the font of selected characters to bold
cell.Characters(6, 7).Font.IsBold = true;
// Setting the font color of selected characters to blue
cell.Characters(6, 7).Font.Color = Color.Blue;
// Saving the Excel file
workbook.Save(dataDir + "book1.out.xls");

Как форматировать строки и столбцы

Иногда разработчику требуется применить одно и то же форматирование на строки или столбцы. Применение форматирования к ячейкам одну за другой часто занимает больше времени и не является хорошим решением. Для решения этой проблемы Aspose.Cells предоставляет простой и быстрый способ, который подробно рассматривается в данной статье.

Форматирование строк и столбцов

Aspose.Cells предоставляет класс, Workbook который представляет файл Microsoft Excel. Класс Workbookсодержит коллекцию Worksheets, которая позволяет получить доступ к каждому листу в файле Excel. Лист представлен классом Worksheet. Класс Worksheet предоставляет коллекцию Cells. Коллекция Cells предоставляет коллекцию Rows.

Как форматировать строку

Каждый элемент в коллекции {0} представляет объект {1}. Объект {2} предлагает метод {3, используемый для установки форматирования строки. Для применения одного и того же форматирования к строке используйте объект {4}. Ниже приведены шаги, как его использовать.

  1. Добавьте объект Style в класс Workbook, вызвав его метод CreateStyle.
  2. Установите свойства объекта Style, чтобы применить настройки форматирования.
  3. Включите соответствующие атрибуты для объекта StyleFlag.
  4. Назначьте настроенный объект Style на объект Row.
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
// Create directory if it is not already present.
bool IsExists = System.IO.Directory.Exists(dataDir);
if (!IsExists)
System.IO.Directory.CreateDirectory(dataDir);
// Instantiating a Workbook object
Workbook workbook = new Workbook();
// Obtaining the reference of the first (default) worksheet by passing its sheet index
Worksheet worksheet = workbook.Worksheets[0];
// Adding a new Style to the styles
Style style = workbook.CreateStyle();
// Setting the vertical alignment of the text in the "A1" cell
style.VerticalAlignment = TextAlignmentType.Center;
// Setting the horizontal alignment of the text in the "A1" cell
style.HorizontalAlignment = TextAlignmentType.Center;
// Setting the font color of the text in the "A1" cell
style.Font.Color = Color.Green;
// Shrinking the text to fit in the cell
style.ShrinkToFit = true;
// Setting the bottom border color of the cell to red
style.Borders[BorderType.BottomBorder].Color = Color.Red;
// Setting the bottom border type of the cell to medium
style.Borders[BorderType.BottomBorder].LineStyle = CellBorderType.Medium;
// Creating StyleFlag
StyleFlag styleFlag = new StyleFlag();
styleFlag.HorizontalAlignment = true;
styleFlag.VerticalAlignment = true;
styleFlag.ShrinkToFit = true;
styleFlag.Borders = true;
styleFlag.FontColor = true;
// Accessing a row from the Rows collection
Row row = worksheet.Cells.Rows[0];
// Assigning the Style object to the Style property of the row
row.ApplyStyle(style, styleFlag);
// Saving the Excel file
workbook.Save(dataDir + "book1.out.xls");

Как форматировать столбец

Коллекция Cells также предоставляет коллекцию Columns. Каждый элемент в коллекции Columns представляет объект Column. Аналогично объекту Row, объект Column также предлагает метод ApplyStyle для форматирования столбца.

// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
// Create directory if it is not already present.
bool IsExists = System.IO.Directory.Exists(dataDir);
if (!IsExists)
System.IO.Directory.CreateDirectory(dataDir);
// Instantiating a Workbook object
Workbook workbook = new Workbook();
// Obtaining the reference of the first (default) worksheet by passing its sheet index
Worksheet worksheet = workbook.Worksheets[0];
// Adding a new Style to the styles
Style style = workbook.CreateStyle();
// Setting the vertical alignment of the text in the "A1" cell
style.VerticalAlignment = TextAlignmentType.Center;
// Setting the horizontal alignment of the text in the "A1" cell
style.HorizontalAlignment = TextAlignmentType.Center;
// Setting the font color of the text in the "A1" cell
style.Font.Color = Color.Green;
// Shrinking the text to fit in the cell
style.ShrinkToFit = true;
// Setting the bottom border color of the cell to red
style.Borders[BorderType.BottomBorder].Color = Color.Red;
// Setting the bottom border type of the cell to medium
style.Borders[BorderType.BottomBorder].LineStyle = CellBorderType.Medium;
// Creating StyleFlag
StyleFlag styleFlag = new StyleFlag();
styleFlag.HorizontalAlignment = true;
styleFlag.VerticalAlignment = true;
styleFlag.ShrinkToFit = true;
styleFlag.Borders = true;
styleFlag.FontColor = true;
// Accessing a column from the Columns collection
Column column = worksheet.Cells.Columns[0];
// Applying the style to the column
column.ApplyStyle(style, styleFlag);
// Saving the Excel file
workbook.Save(dataDir + "book1.out.xls");

Продвинутые темы