Формат ячеек

Вступление

Формат Cells с использованием методов GetStyle и SetStyle

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

Использование методов GetStyle и SetStyle

Если разработчикам нужно применить разные стили форматирования к разным ячейкам, лучше получитьСтиль клетки с помощью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");

Использование объекта стиля для различного форматирования Cells

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

  1. ДобавитьСтиль объект, позвонив вСоздать стиль методРабочая тетрадьучебный класс
  2. Доступ к недавно добавленнымСтильобъект
  3. Установите желаемые свойства/атрибутыСтильобъект для применения желаемых настроек форматирования
  4. Назначьте настроенныйСтильвозражать против желаемых ячеек

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

// 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, примените стили, используя Aspose.Cells API. Ниже приведен пример, демонстрирующий этот подход для применения предопределенного стиля к ячейке.

// 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");

Форматирование выбранных символов в Cell

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

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

Форматирование выбранных символов

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

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

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

Символы метод возвращает экземплярНастройка шрифтакласс, который позволяет разработчикам форматировать символы так же, как и ячейку, как показано ниже в примере кода. В выходном файле в ячейке A1 слово «Посетить» будет отформатировано шрифтом по умолчанию, но «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 предоставляет класс,Рабочая тетрадь который представляет собой файл Excel Microsoft.Рабочая тетрадь класс содержитРабочие листы коллекция, которая обеспечивает доступ к каждому рабочему листу в файле Excel. Рабочий лист представленРабочий лист учебный класс.Рабочий лист класс предоставляетCells коллекция.Cellsколлекция обеспечиваетРядыколлекция.

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

Каждый элемент вРяды коллекция представляет собойСтрока объект.Строкаобъект предлагаетПрименить стиль метод, используемый для установки форматирования строки. Чтобы применить такое же форматирование к строке, используйтеСтильобъект. Шаги ниже показывают, как его использовать.

  1. ДобавитьСтиль возражать противРабочая тетрадь класс, вызвав егоСоздать стильметод.
  2. УстановитьСтильсвойства объекта для применения параметров форматирования.
  3. Включите соответствующие атрибуты дляСтильФлагобъект.
  4. Назначьте настроенныйСтиль возражать противСтрокаобъект.
// 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 коллекция также обеспечиваетСтолбцы коллекция. Каждый элемент вСтолбцы коллекция представляет собойСтолбец объект. Похоже наСтрока объект,Столбец объект также предлагаетПрименить стильметод форматирования столбца.

// 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");

Предварительные темы