Formater les cellules avec JavaScript via C++
Introduction
Comment formater les cellules en utilisant les méthodes de style
Appliquer différents types de styles de formatage sur les cellules pour définir des couleurs de fond ou de premier plan, des bordures, des polices, des alignements horizontaux et verticaux, le niveau d’indentation, la direction du texte, l’angle de rotation et bien plus encore.
Comment utiliser les méthodes de style
Si les développeurs doivent appliquer différents styles de mise en forme à différentes cellules, il est préférable d’obtenir Style de la cellule en utilisant la méthode Cell.style, de spécifier les attributs de style et ensuite d’appliquer la mise en forme avec la méthode Cell.style. Un exemple est donné ci-dessous pour illustrer cette approche d’application de divers styles à une cellule.
<!DOCTYPE html>
<html>
<head>
<title>Aspose.Cells Example</title>
</head>
<body>
<h1>Aspose.Cells Styling Example</h1>
<input type="file" id="fileInput" accept=".xls,.xlsx,.csv" />
<button id="runExample">Run Example</button>
<a id="downloadLink" style="display: none;">Download Result</a>
<div id="result"></div>
</body>
<script src="aspose.cells.js.min.js"></script>
<script type="text/javascript">
const { Workbook, SaveFormat } = AsposeCells;
AsposeCells.onReady({
license: "/lic/aspose.cells.enc",
fontPath: "/fonts/",
fontList: [
"arial.ttf",
"NotoSansSC-Regular.ttf"
]
}).then(() => {
console.log("Aspose.Cells initialized");
});
document.getElementById('runExample').addEventListener('click', async () => {
const fileInput = document.getElementById('fileInput');
// Instantiate or load workbook
let workbook;
if (fileInput.files && fileInput.files.length) {
const file = fileInput.files[0];
const arrayBuffer = await file.arrayBuffer();
workbook = new Workbook(new Uint8Array(arrayBuffer));
} else {
workbook = new Workbook();
}
// Obtaining the reference of the first worksheet
const worksheet = workbook.worksheets.get(0);
// Accessing the "A1" cell from the worksheet
const cell = worksheet.cells.get("A1");
// Adding some value to the "A1" cell
cell.value = "Hello Aspose!";
// Defining a Style object
let style;
// Get the style from A1 cell
style = cell.style;
// Setting the vertical alignment
style.verticalAlignment = AsposeCells.TextAlignmentType.Center;
// Setting the horizontal alignment
style.horizontalAlignment = AsposeCells.TextAlignmentType.Center;
// Setting the font color of the text
style.font.color = AsposeCells.Color.Green;
// Setting to shrink according to the text contained in it
style.shrinkToFit = true;
// Setting the bottom border color to red
style.borders.get(AsposeCells.BorderType.BottomBorder).color = AsposeCells.Color.Red;
// Setting the bottom border type to medium
style.borders.get(AsposeCells.BorderType.BottomBorder).lineStyle = AsposeCells.CellBorderType.Medium;
// Applying the style to A1 cell
cell.style = style;
// Saving the Excel file
const outputData = workbook.save(SaveFormat.Excel97To2003);
const blob = new Blob([outputData]);
const downloadLink = document.getElementById('downloadLink');
downloadLink.href = URL.createObjectURL(blob);
downloadLink.download = 'book1.out.xls';
downloadLink.style.display = 'block';
downloadLink.textContent = 'Download Excel File';
document.getElementById('result').innerHTML = '<p style="color: green;">Operation completed successfully! Click the download link to get the modified file.</p>';
});
</script>
</html>
Comment utiliser l’objet de style pour formater différentes cellules
Si les développeurs doivent appliquer le même style de mise en forme à différentes cellules, ils peuvent utiliser l’objet Style. Veuillez suivre les étapes ci-dessous pour utiliser l’objet Style:
- Ajoutez un objet Style en appelant la méthode createStyle() de la classe Workbook
- Accédez à l’objet Style récemment ajouté
- Définissez les propriétés/attributs souhaités de l’objet Style pour appliquer les paramètres de formatage souhaités
- Assignez l’objet Style configuré à vos cellules souhaitées
Cette approche peut grandement améliorer l’efficacité de vos applications et économiser de la mémoire également.
<!DOCTYPE html>
<html>
<head>
<title>Aspose.Cells Example</title>
</head>
<body>
<h1>Aspose.Cells Example - Create Workbook and Style Cells</h1>
<input type="file" id="fileInput" accept=".xls,.xlsx,.csv" />
<button id="runExample">Run Example</button>
<a id="downloadLink" style="display: none;">Download Result</a>
<div id="result"></div>
</body>
<script src="aspose.cells.js.min.js"></script>
<script type="text/javascript">
const { Workbook, SaveFormat, TextAlignmentType, Color, BorderType, CellBorderType } = AsposeCells;
AsposeCells.onReady({
license: "/lic/aspose.cells.enc",
fontPath: "/fonts/",
fontList: [
"arial.ttf",
"NotoSansSC-Regular.ttf"
]
}).then(() => {
console.log("Aspose.Cells initialized");
});
document.getElementById('runExample').addEventListener('click', async () => {
// Instantiate a new Workbook
const workbook = new Workbook();
// Add a new worksheet to the workbook
const i = workbook.worksheets.add();
// Obtain the newly added worksheet by index
const worksheet = workbook.worksheets.get(i);
// Access cell A1
const cell = worksheet.cells.get("A1");
// Set value of A1
cell.value = "Hello Aspose!";
// Create a new style
const style = workbook.createStyle();
// Set vertical and horizontal alignment
style.verticalAlignment = TextAlignmentType.Center;
style.horizontalAlignment = TextAlignmentType.Center;
// Set font color
style.font.color = Color.Green;
// Shrink to fit
style.shrinkToFit = true;
// Set bottom border color and style
style.borders.get(BorderType.BottomBorder).color = Color.Red;
style.borders.get(BorderType.BottomBorder).lineStyle = CellBorderType.Medium;
// Apply style to A1
cell.style = style;
// Apply same style to B1, C1, D1
worksheet.cells.get("B1").style = style;
worksheet.cells.get("C1").style = style;
worksheet.cells.get("D1").style = style;
// Save workbook to XLS format and provide download link
const outputData = workbook.save(SaveFormat.Excel97To2003);
const blob = new Blob([outputData]);
const downloadLink = document.getElementById('downloadLink');
downloadLink.href = URL.createObjectURL(blob);
downloadLink.download = 'book1.out.xls';
downloadLink.style.display = 'block';
downloadLink.textContent = 'Download Excel File';
document.getElementById('result').innerHTML = '<p style="color: green;">Workbook created and styled successfully! Click the download link to get the file.</p>';
});
</script>
</html>
Comment utiliser les styles prédéfinis de Microsoft Excel 2007
Si vous avez besoin d’appliquer différents styles de formatage pour Microsoft Excel 2007, appliquez les styles en utilisant l’API Aspose.Cells. Un exemple est donné ci-dessous pour illustrer cette approche d’application d’un style prédéfini sur une cellule.
<!DOCTYPE html>
<html>
<head>
<title>Aspose.Cells Example</title>
</head>
<body>
<h1>Create Workbook and Set Cell Style Example</h1>
<input type="file" id="fileInput" accept=".xls,.xlsx,.csv" />
<button id="runExample">Run Example</button>
<a id="downloadLink" style="display: none;">Download Result</a>
<div id="result"></div>
</body>
<script src="aspose.cells.js.min.js"></script>
<script type="text/javascript">
const { Workbook, SaveFormat } = AsposeCells;
AsposeCells.onReady({
license: "/lic/aspose.cells.enc",
fontPath: "/fonts/",
fontList: [
"arial.ttf",
"NotoSansSC-Regular.ttf"
]
}).then(() => {
console.log("Aspose.Cells initialized");
});
document.getElementById('runExample').addEventListener('click', async () => {
// Instantiate a new Workbook.
const workbook = new Workbook();
// Create a style object.
const style = workbook.createStyle();
// Access the first worksheet in the workbook
const worksheet = workbook.worksheets.get(0);
// Access cell A1
const cell = worksheet.cells.get("A1");
// Input a value to A1 cell.
cell.putValue("Test");
// Apply the style to the cell.
cell.style = style;
// Saving the Excel 2007 file.
const outputData = workbook.save(SaveFormat.Xlsx);
const blob = new Blob([outputData]);
const downloadLink = document.getElementById('downloadLink');
downloadLink.href = URL.createObjectURL(blob);
downloadLink.download = 'book1.out.xlsx';
downloadLink.style.display = 'block';
downloadLink.textContent = 'Download Excel File';
document.getElementById('result').innerHTML = '<p style="color: green;">Workbook created successfully! Click the download link to get the file.</p>';
});
</script>
</html>
Comment formater des caractères sélectionnés dans une cellule
La gestion des paramètres de police explique comment formater du texte dans les cellules, mais cela explique seulement comment formater tout le contenu de la cellule. Et si vous voulez formater uniquement des caractères sélectionnés ?
Aspose.Cells prend également en charge cette fonctionnalité. Ce sujet explique comment utiliser cette fonctionnalité efficacement.
Comment formater des caractères sélectionnés
Aspose.Cells fournit une classe, Workbook qui représente un fichier Microsoft Excel. La classe Workbook contient la collection worksheets qui permet d’accéder à chaque feuille de calcul dans un fichier Excel. Une feuille de calcul est représentée par la classe Worksheet. La classe Worksheet offre une collection cells. Chaque élément dans la collection cells représente un objet de la classe Cell.
La classe Cell fournit la méthode characters(number, number) qui prend les paramètres suivants pour sélectionner une plage de caractères à l’intérieur d’une cellule :
- Index de début, l’index du caractère à partir duquel la sélection commence.
- Nombre de caractères, le nombre de caractères à sélectionner.
La méthode characters(number, number) retourne une instance de la classe FontSetting qui permet aux développeurs de formater les caractères de la même manière qu’une cellule, comme illustré ci-dessous dans l’exemple de code. Dans le fichier de sortie, dans la cellule A1, le mot ‘Visit’ sera formaté avec la police par défaut, mais ‘Aspose!’ sera en gras et en bleu.
<!DOCTYPE html>
<html>
<head>
<title>Aspose.Cells Example</title>
<meta charset="utf-8" />
</head>
<body>
<h1>Aspose.Cells Example</h1>
<input type="file" id="fileInput" accept=".xls,.xlsx,.csv" />
<button id="runExample">Run Example</button>
<a id="downloadLink" style="display: none;">Download Result</a>
<div id="result"></div>
</body>
<script src="aspose.cells.js.min.js"></script>
<script type="text/javascript">
const { Workbook, SaveFormat } = AsposeCells;
AsposeCells.onReady({
license: "/lic/aspose.cells.enc",
fontPath: "/fonts/",
fontList: [
"arial.ttf",
"NotoSansSC-Regular.ttf"
]
}).then(() => {
console.log("Aspose.Cells initialized");
});
document.getElementById('runExample').addEventListener('click', async () => {
const fileInput = document.getElementById('fileInput');
// If a file is provided, open it; otherwise create a new workbook
let workbook;
if (fileInput.files && fileInput.files.length > 0) {
const file = fileInput.files[0];
const arrayBuffer = await file.arrayBuffer();
workbook = new Workbook(new Uint8Array(arrayBuffer));
} else {
workbook = new Workbook();
}
// Obtaining the reference of the first (default) worksheet by passing its sheet index
const worksheet = workbook.worksheets.get(0);
// Accessing the "A1" cell from the worksheet
const cell = worksheet.cells.get("A1");
// Adding some value to the "A1" cell
cell.value = "Visit Aspose!";
// Setting the font of selected characters to bold and color to blue
const charRange = cell.characters(6, 7);
charRange.font.isBold = true;
charRange.font.color = AsposeCells.Color.Blue;
// Saving the Excel file
const outputData = workbook.save(SaveFormat.Excel97To2003);
const blob = new Blob([outputData]);
const downloadLink = document.getElementById('downloadLink');
downloadLink.href = URL.createObjectURL(blob);
downloadLink.download = 'book1.out.xls';
downloadLink.style.display = 'block';
downloadLink.textContent = 'Download Excel File';
document.getElementById('result').innerHTML = '<p style="color: green;">Operation completed successfully! Click the download link to get the modified file.</p>';
});
</script>
</html>
Comment formater les lignes et les colonnes
Parfois, les développeurs doivent appliquer le même formatage sur des lignes ou des colonnes. Appliquer le formatage sur chaque cellule prend souvent plus de temps et n’est pas une bonne solution. Pour résoudre ce problème, Aspose.Cells offre une solution simple et rapide qui est discutée en détail dans cet article.
Mise en forme des lignes & colonnes
Aspose.Cells fournit une classe, Workbook qui représente un fichier Microsoft Excel. La classe Workbook contient une collection worksheets qui permet d’accéder à chaque feuille de calcul dans le fichier Excel. Une feuille de calcul est représentée par la classe Worksheet. La classe Worksheet offre une collection cells. La collection cells offre une collection rows.
Comment formater une ligne
Chaque élément de la collection rows représente un objet Row. L’objet Row offre la méthode applyStyle(Style, StyleFlag) utilisée pour définir la mise en forme de la ligne. Pour appliquer la même mise en forme à une ligne, utilisez l’objet Style. Les étapes ci-dessous montrent comment l’utiliser.
- Ajoutez un objet Style à la classe Workbook en appelant sa méthode createStyle().
- Définissez les propriétés de l’objet Style pour appliquer les paramètres de mise en forme.
- Activez les attributs pertinents pour l’objet StyleFlag.
- Assignez l’objet Style configuré à l’objet Row.
<!DOCTYPE html>
<html>
<head>
<title>Aspose.Cells Example</title>
</head>
<body>
<h1>Aspose.Cells Example</h1>
<input type="file" id="fileInput" accept=".xls,.xlsx,.csv" />
<button id="runExample">Run Example</button>
<a id="downloadLink" style="display: none;">Download Result</a>
<div id="result"></div>
</body>
<script src="aspose.cells.js.min.js"></script>
<script type="text/javascript">
const { Workbook, SaveFormat } = AsposeCells;
AsposeCells.onReady({
license: "/lic/aspose.cells.enc",
fontPath: "/fonts/",
fontList: [
"arial.ttf",
"NotoSansSC-Regular.ttf"
]
}).then(() => {
console.log("Aspose.Cells initialized");
});
document.getElementById('runExample').addEventListener('click', async () => {
// Instantiating a Workbook object
const workbook = new Workbook();
// Obtaining the reference of the first (default) worksheet by passing its sheet index
const worksheet = workbook.worksheets.get(0);
// Adding a new Style to the styles
const style = workbook.createStyle();
// Setting the vertical alignment of the text in the "A1" cell
style.verticalAlignment = AsposeCells.TextAlignmentType.Center;
// Setting the horizontal alignment of the text in the "A1" cell
style.horizontalAlignment = AsposeCells.TextAlignmentType.Center;
// Setting the font color of the text in the "A1" cell
style.font.color = AsposeCells.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.get(AsposeCells.BorderType.BottomBorder).color = AsposeCells.Color.Red;
// Setting the bottom border type of the cell to medium
style.borders.get(AsposeCells.BorderType.BottomBorder).lineStyle = AsposeCells.CellBorderType.Medium;
// Creating StyleFlag
const styleFlag = new AsposeCells.StyleFlag();
styleFlag.horizontalAlignment = true;
styleFlag.verticalAlignment = true;
styleFlag.shrinkToFit = true;
styleFlag.borders = true;
styleFlag.fontColor = true;
// Accessing a row from the Rows collection
const row = worksheet.cells.rows.get(0);
// Assigning the Style object to the Style property of the row
row.applyStyle(style, styleFlag);
// Saving the Excel file
const outputData = workbook.save(SaveFormat.Excel97To2003);
const blob = new Blob([outputData]);
const downloadLink = document.getElementById('downloadLink');
downloadLink.href = URL.createObjectURL(blob);
downloadLink.download = 'book1.out.xls';
downloadLink.style.display = 'block';
downloadLink.textContent = 'Download Modified Excel File';
document.getElementById('result').innerHTML = '<p style="color: green;">Operation completed successfully! Click the download link to get the modified file.</p>';
});
</script>
</html>
Comment formater une colonne
La collection cells offre également une collection columns. Chaque élément dans la collection columns représente un objet Column. Semblable à un objet Row, l’objet Column offre également la méthode applyStyle(Style, StyleFlag) pour formater une colonne.
<!DOCTYPE html>
<html>
<head>
<title>Aspose.Cells Example</title>
</head>
<body>
<h1>Aspose.Cells Style and Column Apply Example</h1>
<input type="file" id="fileInput" accept=".xls,.xlsx,.csv" />
<button id="runExample">Run Example</button>
<a id="downloadLink" style="display: none;">Download Result</a>
<div id="result"></div>
</body>
<script src="aspose.cells.js.min.js"></script>
<script type="text/javascript">
const { Workbook, SaveFormat } = AsposeCells;
AsposeCells.onReady({
license: "/lic/aspose.cells.enc",
fontPath: "/fonts/",
fontList: [
"arial.ttf",
"NotoSansSC-Regular.ttf"
]
}).then(() => {
console.log("Aspose.Cells initialized");
});
document.getElementById('runExample').addEventListener('click', async () => {
// Instantiate a new Workbook
const workbook = new Workbook();
// Obtain the first worksheet
const worksheet = workbook.worksheets.get(0);
// Add a new Style to the styles
const style = workbook.createStyle();
// Set vertical and horizontal alignment
style.verticalAlignment = AsposeCells.TextAlignmentType.Center;
style.horizontalAlignment = AsposeCells.TextAlignmentType.Center;
// Set font color
style.font.color = AsposeCells.Color.Green;
// Shrink to fit
style.shrinkToFit = true;
// Set bottom border color and style
style.borders.get(AsposeCells.BorderType.BottomBorder).color = AsposeCells.Color.Red;
style.borders.get(AsposeCells.BorderType.BottomBorder).lineStyle = AsposeCells.CellBorderType.Medium;
// Create and configure StyleFlag
const styleFlag = new AsposeCells.StyleFlag();
styleFlag.horizontalAlignment = true;
styleFlag.verticalAlignment = true;
styleFlag.shrinkToFit = true;
styleFlag.borders = true;
styleFlag.fontColor = true;
// Access first column and apply style
const column = worksheet.cells.getColumns().get(0);
column.applyStyle(style, styleFlag);
// Save the workbook and provide download link
const outputData = workbook.save(SaveFormat.Excel97To2003);
const blob = new Blob([outputData]);
const downloadLink = document.getElementById('downloadLink');
downloadLink.href = URL.createObjectURL(blob);
downloadLink.download = 'book1.out.xls';
downloadLink.style.display = 'block';
downloadLink.textContent = 'Download Modified Excel File';
document.getElementById('result').innerHTML = '<p style="color: green;">Style applied to column successfully! Click the download link to get the modified file.</p>';
});
</script>
</html>
Sujets avancés
- Paramètres d’alignement
- Paramètres de bordure
- Définir les formats conditionnels des fichiers Excel et ODS.
- Thèmes et couleurs d’Excel
- Paramètres de remplissage
- Paramètres de police
- Formater les cellules de feuille de calcul dans un classeur
- Mise en œuvre du système de date 1904
- Fusionner et scinder des cellules
- Paramètres de nombre
- Obtenir et définir le style des cellules