Dokument ukazuje, jak vygenerovat soubor Excel v C#. Následující kroky a úryvek kódu ukazují, jak vytvořit soubor Excel v C# bez použití interoperability MS Office.
Kroky k generování souboru Excel v C#
- Stáhněte si nebo nainstalujte balíček Aspose.Cells for .NET z NuGet.org
- Importujte jmenný prostor Aspose.Cells do projektu VS.NET
- Definujte objekt License a nastavte jej pomocí metody SetLicense
- Vytvořte prázdný Workbook
- Zadejte data přehledu do buněk prvního Worksheet
- Uložte soubor Excel XLSX s daty
V průběhu let je známo, že formáty souborů MS Excel se používají pro analýzu dat a reportování dat. Výše uvedené kroky popisují postup zápisu do souboru Excel pomocí C#. Píšeme kód C#, abychom od začátku vytvořili nový soubor Excel. Soubor Excel bude obsahovat vzorovou zprávu o zákaznících; můžete vytvořit požadovanou sestavu vyplněním příslušných buněk daty v listu.
Ukázkový kód pro generování souboru Excel v C#
//Add reference to the namespace of Aspose.Cells for .NET | |
using Aspose.Cells; | |
namespace GenerateExcelFile | |
{ | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
//At the start, set the license before using other APIs | |
Aspose.Cells.License Aspose_Cells_license = new Aspose.Cells.License(); | |
Aspose_Cells_license.SetLicense("Aspose.Cells.lic"); | |
//Create an Excel workbook from the scratch | |
Workbook ExcelFileWorkbook = new Workbook(); | |
//Get the first worksheet (0 indexed position) in the workbook, the default worksheet | |
Worksheet ExcelFileSheet = ExcelFileWorkbook.Worksheets[0]; | |
//Get the cells collection in the default worksheet | |
Cells SheetCells = ExcelFileSheet.Cells; | |
//Insert data into the cells of the sheet | |
SheetCells["A1"].PutValue("Customers Report"); | |
SheetCells["A2"].PutValue("C_ID"); | |
SheetCells["B2"].PutValue("C_Name"); | |
SheetCells["A3"].PutValue("C001"); | |
SheetCells["B3"].PutValue("Customer1"); | |
SheetCells["A4"].PutValue("C002"); | |
SheetCells["B4"].PutValue("Customer2"); | |
SheetCells["A5"].PutValue("C003"); | |
SheetCells["B5"].PutValue("Customer3"); | |
SheetCells["A6"].PutValue("C004"); | |
SheetCells["B6"].PutValue("Customer4"); | |
//Save to Excel file (XLSX) | |
ExcelFileWorkbook.Save("ExcelFile.xlsx"); | |
} | |
} | |
} |
Ve výše uvedeném příkladu se naučíte, jak vytvořit soubor Excel dynamicky v C#. Pomocí C#.NET můžete snadno vytvořit soubor Excel. Ve fragmentu kódu vložíme data do několika buněk prvního listu v sešitu, abychom vytvořili jednoduchou sestavu. Nakonec soubor Excel XLSX uložíme na disk. Kromě toho se vám může líbit jak exportovat velký soubor Excel do CSV v C#.