Introducció

Aspose.Cells FOSS for .NET és una biblioteca de codi gestionat pur, amb llicència MIT, per a la lectura, escriptura, i manipulació de llibres de treball d’Excel .xlsx sense cap dependència de Microsoft Office. Instal·lat com el paquet NuGet Aspose.Cells_FOSS, s’integra en qualsevol projecte .NET — aplicacions de consola, APIs web, treballadors en segon pla i funcions sense servidor.

Aquesta publicació ofereix una guia pas a pas de les característiques de l’API pública, mostrant què és possible i com invocar cada capacitat des del codi C#.


Visió general de la característica

Cicle de vida del llibre de treball i del full de càlcul

L’punt d’entrada per a cada operació és la classe Workbook. Construïu-ne una des de zero amb new Workbook(), o carregueu una existent .xlsx amb new Workbook(filePath) o new Workbook(stream). Navegueu per les fulles mitjançant Workbook.Worksheets, establiu Worksheet.Name i Worksheet.VisibilityType, i persisteu amb Workbook.Save(). Per a fitxers danyats, passeu una instància LoadOptions amb TryRepairPackage = true i TryRepairXml = true.

using Aspose.Cells_FOSS;

var options = new LoadOptions
{
    TryRepairPackage = true,
    TryRepairXml = true,
};

try
{
    _ = new Workbook("sample.xlsx", options);
}
catch (WorkbookLoadException exception)
{
    Console.WriteLine(exception.Message);
}

Dades i fórmules de cel·la

Escriu valors a les cel·les amb Cell.PutValue() — les sobrecàrregues accepten string, int, double, decimal, bool i DateTime. Llegeix els valors de tornada mitjançant Cell.Value, Cell.StringValue i Cell.Formula. Defineix fórmules d’Excel amb la propietat Cell.Formula; la cadena de la fórmula es conserva en desar i sobreviu a un cicle de recàrrega.

using Aspose.Cells_FOSS;

var workbook = new Workbook();
var sheet = workbook.Worksheets[0];
sheet.Cells["A1"].PutValue("Hello");
sheet.Cells["B1"].PutValue(123);
sheet.Cells["C1"].Formula = "=B1*2";

workbook.Save("hello.xlsx");

var loaded = new Workbook("hello.xlsx");
Console.WriteLine(loaded.Worksheets[0].Cells["C1"].Formula);
Console.WriteLine(loaded.Worksheets[0].Cells["C1"].StringValue);

Estil de cel·la

Aplica els objectes Style per controlar la tipografia, el farciment, les vores, el format de número i l’alineació.
Recupera l’estil actual amb Cell.GetStyle(), modifica’l i, a continuació, confirma-ho amb
Cell.SetStyle(). Per als farciments de fons, estableix Style.Pattern = FillPattern.Solid i assigna un
Color a Style.ForegroundColor. Utilitza Cells.Merge() per abastar intervals de cel·les.

using Aspose.Cells_FOSS;

var workbook = new Workbook();
var cell = workbook.Worksheets[0].Cells["A1"];
cell.PutValue("Styled");

var style = cell.GetStyle();
style.Font.Bold = true;
style.Pattern = FillPattern.Solid;
style.ForegroundColor = Color.FromArgb(255, 241, 196, 15);
cell.SetStyle(style);

Console.WriteLine($"{cell.StringValue} / Bold={cell.GetStyle().Font.Bold}");

Formatació condicional

Adjunta regles de formatatge condicional a intervals de cel·les mitjançant ConditionalFormattingCollection.
Les regles admeten FormatConditionType.CellValue, Expression, ColorScale, DataBar i
IconSet. Utilitza OperatorType per especificar operadors de comparació (Between, Equal,
GreaterThan, etc.), assigna un Style a les cel·les coincidents i configura la prioritat i
el comportament stop-if-true per regla.

using Aspose.Cells_FOSS;

var workbook = new Workbook();
var sheet = workbook.Worksheets[0];

var cfCollection = sheet.ConditionalFormattings[sheet.ConditionalFormattings.Add()];
cfCollection.AddArea(CellArea.CreateCellArea("A1", "A10"));
var rule = cfCollection[cfCollection.AddCondition(
    FormatConditionType.CellValue, OperatorType.Between, "3", "7")];
var style = rule.Style;
style.Pattern = FillPattern.Solid;
style.ForegroundColor = Color.FromArgb(255, 255, 199, 206);
style.Font.Bold = true;
rule.Style = style;

workbook.Save("conditional-formatting.xlsx");

Validació de dades

Afegiu restriccions d’entrada a les cel·les utilitzant Worksheet.Validations. Els tipus de validació compatibles inclouen ValidationType.List, Decimal, Custom i més. Configureu indicacions d’entrada (InputTitle, InputMessage) i missatges d’error (ErrorTitle, ErrorMessage, ValidationAlertType). Utilitzeu CellArea.CreateCellArea() per definir el rang validat i Validation.AddArea() per aplicar una regla a rangs addicionals.

using Aspose.Cells_FOSS;

var workbook = new Workbook();
var sheet = workbook.Worksheets[0];
sheet.Name = "Validation Sheet";

var listIdx = sheet.Validations.Add(CellArea.CreateCellArea("A1", "A3"));
var listVal = sheet.Validations[listIdx];
listVal.Type = ValidationType.List;
listVal.Formula1 = "\"Open,Closed\"";
listVal.IgnoreBlank = true;
listVal.InCellDropDown = true;
listVal.ShowInput = true;
listVal.InputTitle = "Status";
listVal.InputMessage = "Pick a status";
listVal.ShowError = true;
listVal.ErrorTitle = "Invalid";
listVal.ErrorMessage = "Choose from the list";

workbook.Save("validations-sample.xlsx");

Configuració de pàgina i opcions d’impressió

Configureu el disseny d’impressió mitjançant Worksheet.PageSetup. Establiu els marges (LeftMarginInch, RightMarginInch, TopMarginInch, BottomMarginInch), Orientation, PaperSize, escala, àrea d’impressió, files i columnes de títol, capçaleres i peus de pàgina, i salts de pàgina. Tots els paràmetres sobreviuen una ronda de desar‑carregar.

using Aspose.Cells_FOSS;

var workbook = new Workbook();
var sheet = workbook.Worksheets[0];
sheet.Name = "Print Sheet";
sheet.Cells["A1"].PutValue("Title");

var pageSetup = sheet.PageSetup;
pageSetup.Orientation = PageOrientationType.Landscape;
pageSetup.PaperSize = PaperSizeType.PaperA4;
pageSetup.PrintArea = "$A$1:$C$10";
pageSetup.PrintTitleRows = "$1:$2";
pageSetup.LeftHeader = "Left Header";
pageSetup.CenterFooter = "Center Footer";
pageSetup.PrintGridlines = true;
pageSetup.CenterHorizontally = true;

workbook.Save("page-setup-sample.xlsx");

Configuració i protecció del full de càlcul

Control de visualització per full amb Worksheet.ShowGridlines, ShowRowColumnHeaders, ShowZeros, RightToLeft, Zoom i TabColor. Protegeix els fulls amb Worksheet.Protect() i configura banderes de gran precisió Protection (Objects, FormatCells, InsertRows, AutoFilter, SelectLockedCells). Gestiona l’alçada de les files, l’amplada de les columnes, files/columnes ocultes i regions fusionades mitjançant Cells.Rows, Cells.Columns i Cells.Merge().

using Aspose.Cells_FOSS;

var workbook = new Workbook();
var layout = workbook.Worksheets[0];
layout.Name = "Layout";
layout.VisibilityType = VisibilityType.Hidden;
layout.TabColor = Color.FromArgb(255, 34, 68, 102);
layout.ShowGridlines = false;
layout.Zoom = 85;
layout.Protect();
layout.Protection.FormatCells = true;
layout.Protection.InsertRows = true;

layout.Cells["A1"].PutValue("Merged");
layout.Cells.Rows[1].Height = 22.5d;
layout.Cells.Columns[0].Width = 18.25d;
layout.Cells.Merge(0, 0, 2, 2);

workbook.Save("worksheet-settings-sample.xlsx");

Enllaços i rangs amb nom

Afegeix enllaços externs, interns i mailto: mitjançant HyperlinkCollection.Add(). Defineix Hyperlink.TextToDisplay i Hyperlink.ScreenTip per a etiquetes visibles per a l’usuari. Defineix àrees amb nom a l’àmbit del llibre de treball o del full mitjançant DefinedNameCollection.Add() — les àrees amb nom serveixen com a àncores d’equacions estables i fonts de dades de gràfics que sobreviuen a la recàrrega del fitxer.

using Aspose.Cells_FOSS;

var workbook = new Workbook();
var sheet = workbook.Worksheets[0];

sheet.Cells["A1"].PutValue("Docs");
var link = sheet.Hyperlinks[sheet.Hyperlinks.Add("A1", 1, 1, "https://example.com/docs")];
link.TextToDisplay = "Docs";
link.ScreenTip = "External documentation";

var name = workbook.DefinedNames[workbook.DefinedNames.Add("PrimaryRange", "='Sheet1'!$A$1:$D$5")];
name.Comment = "Primary data range";

workbook.Save("hyperlinks-names.xlsx");
Console.WriteLine("Hyperlinks: " + sheet.Hyperlinks.Count);
Console.WriteLine("Defined names: " + workbook.DefinedNames.Count);

Inici ràpid

dotnet add package Aspose.Cells_FOSS
using Aspose.Cells_FOSS;

var workbook = new Workbook();
var sheet = workbook.Worksheets[0];
sheet.Cells["A1"].PutValue("Hello");
sheet.Cells["B1"].PutValue(123);
sheet.Cells["C1"].Formula = "=B1*2";
workbook.Save("output.xlsx");

Formats compatibles

FormatExtensióLecturaEscriptura
Xlsx.xlsx
Auto(various)

Codi obert i llicències

Aspose.Cells FOSS per .NET es publica sota la llicència MIT i es distribueix via NuGet com a Aspose.Cells_FOSS. És adequat tant per a projectes de codi obert com comercials.


Començar

Recursos relacionats