Altbilgi içeriğine atla
IRONXL KULLANARAK

IronXL Kullanarak C# ile Excel Dosyaları Nasıl Oluşturulur

C# ile programlama yoluyla Excel calismasi dosyalari oluşturmak geleneksel olarak Microsoft Office kurulumunu veya karmasik COM Interop gerektirirdi. IronXL bu durumu tamamen değiştirerek, Excel dosyalarini hicbir Office bagimliligina gerek olmadan oluşturan basit bir API sunar. Bu ders, IronXL kullanarak C#'ta Excel dosyalari oluşturmanin her asamasini kapsar, temel tablo yaratmadan gelişmiş formatlama ve veri tabani entegrasyonuna kadar. Raporlar oluşturuyor, veri aktariyor (XLS veya XLSX dosyalari) ya da tablo uretimini otomatiklestiriyor olun, .NET uygulamalarinda Excel ile calisma icin temel teknikleri ogreneceksiniz.

C# Kullanarak IronXL ile Excel Dosyası Oluşturma: Görüntü 1 - IronXL

Microsoft Office Olmadan Excel Dosyası Oluşturmanın Nedenleri?

Office bagimliliklari olmadan Excel oluşturma özellikleri geliştirmek kritik dağıtim sorunlarini cozer. Sunucu ortamlarinda lisans maliyetleri ve kaynak yukleri nedeniyle Microsoft Office nadiren yukludur. Her Office kurulumu, disk alani ve bellek ihtiyaçi acisindan onemlidir, bu da cloud dağıtımlar veya konteyner uygulanmalari icin pratik degildir.

IronXL bu kisitlamalari bagimsiz calismalar sunarak ortadan kaldiriyor. C# Excel dosya oluşturmaniz Windows, Linux, macOS, Docker konteynerleri veya Azure App Services uzerinde değişiklik yapmadan calisir. Bu capraz platform uyumlulugu, bir kez yazip her yerde yayimlamaya imkan tanir, ister .NET Framework, .NET Core, ya da .NET 10 uygulamalarini hedeflerken.

C# Kullanarak IronXL ile Excel Dosyası Oluşturma: Görüntü 2 - Çapraz Platform

PERFORMANS, COM Interop yuku olmadan dramatik biçimde iyilesir. Geleneksel Office otomasyonu, her işlem için ayrı işlem örnekleri oluşturur, bellek ve CPU kaynakları tüketir. IronXL, herseyin bellek icinde, uygulamanizin işlem alaninda calismasini saglar, bu nedenle programlama yoluyla Excel dosyalari oluşturdugunuzda daha hizli calisma ve daha dusuk kaynak tuketimiyle sonuc verir.

Dağıtım, IronXL'nin tek bir NuGet paketi olarak sağlanmasıyla son derece basitleşir. Kayıt defteri girdileri yok, COM kaydi yok, ve bakim yapacak Office hizmet paketleri yok. Kesintisiz entegrasyon surecleri sorunsuz isler ve Docker konteynerleri hafif kalir. Bu basitlestirilmis yaklasim, IronXL'uni popüler bir seçenek haline getirdi, ve profesyonellerin Excel otomasyonu ile ilgili deneyimlerini paylastigi çeşitli geliştirici forumlarinda ele alinmaktadir.

Bazi geliştiriciler hala dogrudan Office Open XML dosya yapii ile calistmak icin Microsoft'un Open XML Productivity Tool'u kesfetmektedir. Yine de, bu yaklasim daha fazla manuel caba ve XML semasi ile Open XML SDK kurulumuna dair ayrintili bilgi gerektirir. IronXL bu karmasikliklari soyutlayarak, Excel ile programli calisma icin çok daha hizli bir yol sunar.

C# Kullanarak IronXL ile Excel Dosyası Oluşturma: Görüntü 3 - Özellikler

C# Projesine IronXL Nasıl Yüklenir?

IronXL'nin kurulumu, Visual Studio'daki NuGet Paket Yöneticisi aracılığıyla sadece anlar alir. Solution Explorer'da projenize sag tiklayin ve "NuGet Paketlerini Yonet" secenegini secin. "IronXl.Excel" arayin ve Kur'a tiklayin. Paket, C#'ta Excel dosyalarını oluşturmak için gerekli tüm bağımlılıkları otomatik olarak içerir.

Paket Yonetici Konsolu veya .NET CLI araciligiyla kurmak icin, asagidaki komutlardan birini kullanin:

Install-Package IronXl.Excel
dotnet add package IronXl.Excel
Install-Package IronXl.Excel
dotnet add package IronXl.Excel
SHELL

C# Kullanarak IronXL ile Excel Dosyası Oluşturma: Görüntü 4 - Kurulum

Kutuphane hazirlugim olup olmadigini doğrulamak icin bu basit testi yapin:

using IronXL;
// Create an in-memory workbook
var workbook = WorkBook.Create();
Console.WriteLine("IronXL installed successfully!");
using IronXL;
// Create an in-memory workbook
var workbook = WorkBook.Create();
Console.WriteLine("IronXL installed successfully!");
Imports IronXL

' Create an in-memory workbook
Dim workbook = WorkBook.Create()
Console.WriteLine("IronXL installed successfully!")
$vbLabelText   $csharpLabel

Eger bu sorunsuz calisirsa, IronXL kullanima hazirdir. Kütüphane, mevcut projelerinizle uyumluluğu sağlamak için tüm modern .NET sürümlerini destekler. Detayli kurulum rehberligi ve sorun giderme icin, resmi NuGet kurulum dokümanini inceleyin.

Çıktı

C# Kullanarak IronXL ile Excel Dosyası Oluşturma: Görüntü 5 - Konsol Çıkışı

Ilk Excel Dosyanizi Nasıl Oluşturursunuz?

IronXL ile Excel dosyalari oluşturmak, tüm Excel islevlerine erişiminizi saglayan WorkBook sinifi ile başlar. Kutuphane, hem modern XLSX hem de eski XLS formatlarini destekleyerek, C#'ta Excel dosyasi oluşturdugunuzda farkli gereksinimler icin esneklik saglar.

using IronXL;
// Create a new workbook (XLSX format by default)
WorkBook workbook = WorkBook.Create(ExcelFileFormat.XLSX);
// Add metadata
workbook.Metadata.Title = "Monthly Sales Report";
workbook.Metadata.Author = "Sales Department";
workbook.Metadata.Comments = "Generated using IronXL";
// Create a worksheet
WorkSheet worksheet = workbook.CreateWorkSheet("January Sales");
// Add header row
worksheet["A1"].Value = "Date";
worksheet["B1"].Value = "Product";
worksheet["C1"].Value = "Quantity";
worksheet["D1"].Value = "Revenue";
// Add data rows
worksheet["A2"].Value = new DateTime(2024, 1, 15);
worksheet["B2"].Value = "Widget Pro";
worksheet["C2"].Value = 100;
worksheet["D2"].Value = 2500.00;
// Save the workbook
workbook.SaveAs("FirstExcelFile.xlsx");
using IronXL;
// Create a new workbook (XLSX format by default)
WorkBook workbook = WorkBook.Create(ExcelFileFormat.XLSX);
// Add metadata
workbook.Metadata.Title = "Monthly Sales Report";
workbook.Metadata.Author = "Sales Department";
workbook.Metadata.Comments = "Generated using IronXL";
// Create a worksheet
WorkSheet worksheet = workbook.CreateWorkSheet("January Sales");
// Add header row
worksheet["A1"].Value = "Date";
worksheet["B1"].Value = "Product";
worksheet["C1"].Value = "Quantity";
worksheet["D1"].Value = "Revenue";
// Add data rows
worksheet["A2"].Value = new DateTime(2024, 1, 15);
worksheet["B2"].Value = "Widget Pro";
worksheet["C2"].Value = 100;
worksheet["D2"].Value = 2500.00;
// Save the workbook
workbook.SaveAs("FirstExcelFile.xlsx");
Imports IronXL

' Create a new workbook (XLSX format by default)
Dim workbook As WorkBook = WorkBook.Create(ExcelFileFormat.XLSX)

' Add metadata
workbook.Metadata.Title = "Monthly Sales Report"
workbook.Metadata.Author = "Sales Department"
workbook.Metadata.Comments = "Generated using IronXL"

' Create a worksheet
Dim worksheet As WorkSheet = workbook.CreateWorkSheet("January Sales")

' Add header row
worksheet("A1").Value = "Date"
worksheet("B1").Value = "Product"
worksheet("C1").Value = "Quantity"
worksheet("D1").Value = "Revenue"

' Add data rows
worksheet("A2").Value = New DateTime(2024, 1, 15)
worksheet("B2").Value = "Widget Pro"
worksheet("C2").Value = 100
worksheet("D2").Value = 2500.0

' Save the workbook
workbook.SaveAs("FirstExcelFile.xlsx")
$vbLabelText   $csharpLabel

Bu kod, Excel dosya oluşturma icin bircok temel konsepti gösterir. WorkBook.Create() yöntemi, bellekte yeni bir Excel dosyası başlatır. Formatı ExcelFileFormat enumunu kullanarak belirtirsiniz -- modern Excel uyumluluğu için XLSX veya eski destek için XLS seçin. Metadata özelliği, Microsoft'un belge özellik standartlarına uygun olarak Excel'in dosya özelliklerinde görünen belge bilgilerini eklemenizi sağlar.

CreateWorkSheet() yöntemi, belirtilen adla yeni bir sayfa ekler. Excel'in tanidik hucre notasyonu (A1, B1, vb.) değer atanmasını sezgisel hale getirir. IronXL, veri turu donusumlerini otomatik olarak yonetir, tarihleri, sayilari ve metinleri acik bir sekilde atama yapmadan tanir. SaveAs() yöntemi, tamamlanmış Excel dosyasını disk üzerine yazar. Daha fazla calisma sayfasi işlemleri icin, Excel dosyasi yazma rehberini inceleyin.

Çıktı

C# Kullanarak IronXL ile Excel Dosyası Oluşturma: Görüntü 6 - Temel Excel Çıkışı

Excel Hucrelerine Veri Nasıl Yazilir?

IronXL, Excel hücrelerini doldurmak icin bireysel hucre atamalarindan toplu alan islevlerine kadar bircok yöntem sunar. Bu metodlarin anlasilmasi, bir Excel dosyasina yazarken veri senaryonuz icin en verimli yaklasimi secmenizde yardimci olur.

using IronXL;
WorkBook workbook = WorkBook.Create(ExcelFileFormat.XLSX);
WorkSheet worksheet = workbook.CreateWorkSheet("Employees");
// Individual cell assignment
worksheet["A1"].Value = "Employee Name";
worksheet["A2"].Value = "John Smith";
worksheet["A3"].Value = "Jane Doe";
// Range assignment for multiple cells at once
worksheet["B1:B3"].Value = "Active";
// Using numeric indices (0-based row, 0-based column)
worksheet.SetCellValue(0, 2, "Department"); // C1
worksheet.SetCellValue(1, 2, "Sales");       // C2
worksheet.SetCellValue(2, 2, "Marketing");   // C3
// Array-based header population
string[] headers = { "ID", "Name", "Email", "Phone" };
for (int i = 0; i < headers.Length; i++)
{
    worksheet.SetCellValue(0, i, headers[i]);
}
// Working with different data types
worksheet["E1"].Value = "Salary";
worksheet["E2"].Value = 75000.50m;  // Decimal for currency
worksheet["E3"].Value = 82000.75m;
worksheet["F1"].Value = "Start Date";
worksheet["F2"].Value = new DateTime(2020, 3, 15);
worksheet["F3"].Value = new DateTime(2019, 7, 1);
worksheet["G1"].Value = "Full Time";
worksheet["G2"].Value = true;  // Boolean
worksheet["G3"].Value = true;
workbook.SaveAs("EmployeeData.xlsx");
using IronXL;
WorkBook workbook = WorkBook.Create(ExcelFileFormat.XLSX);
WorkSheet worksheet = workbook.CreateWorkSheet("Employees");
// Individual cell assignment
worksheet["A1"].Value = "Employee Name";
worksheet["A2"].Value = "John Smith";
worksheet["A3"].Value = "Jane Doe";
// Range assignment for multiple cells at once
worksheet["B1:B3"].Value = "Active";
// Using numeric indices (0-based row, 0-based column)
worksheet.SetCellValue(0, 2, "Department"); // C1
worksheet.SetCellValue(1, 2, "Sales");       // C2
worksheet.SetCellValue(2, 2, "Marketing");   // C3
// Array-based header population
string[] headers = { "ID", "Name", "Email", "Phone" };
for (int i = 0; i < headers.Length; i++)
{
    worksheet.SetCellValue(0, i, headers[i]);
}
// Working with different data types
worksheet["E1"].Value = "Salary";
worksheet["E2"].Value = 75000.50m;  // Decimal for currency
worksheet["E3"].Value = 82000.75m;
worksheet["F1"].Value = "Start Date";
worksheet["F2"].Value = new DateTime(2020, 3, 15);
worksheet["F3"].Value = new DateTime(2019, 7, 1);
worksheet["G1"].Value = "Full Time";
worksheet["G2"].Value = true;  // Boolean
worksheet["G3"].Value = true;
workbook.SaveAs("EmployeeData.xlsx");
Imports IronXL

Dim workbook As WorkBook = WorkBook.Create(ExcelFileFormat.XLSX)
Dim worksheet As WorkSheet = workbook.CreateWorkSheet("Employees")
' Individual cell assignment
worksheet("A1").Value = "Employee Name"
worksheet("A2").Value = "John Smith"
worksheet("A3").Value = "Jane Doe"
' Range assignment for multiple cells at once
worksheet("B1:B3").Value = "Active"
' Using numeric indices (0-based row, 0-based column)
worksheet.SetCellValue(0, 2, "Department") ' C1
worksheet.SetCellValue(1, 2, "Sales") ' C2
worksheet.SetCellValue(2, 2, "Marketing") ' C3
' Array-based header population
Dim headers As String() = {"ID", "Name", "Email", "Phone"}
For i As Integer = 0 To headers.Length - 1
    worksheet.SetCellValue(0, i, headers(i))
Next
' Working with different data types
worksheet("E1").Value = "Salary"
worksheet("E2").Value = 75000.5D ' Decimal for currency
worksheet("E3").Value = 82000.75D
worksheet("F1").Value = "Start Date"
worksheet("F2").Value = New DateTime(2020, 3, 15)
worksheet("F3").Value = New DateTime(2019, 7, 1)
worksheet("G1").Value = "Full Time"
worksheet("G2").Value = True ' Boolean
worksheet("G3").Value = True
workbook.SaveAs("EmployeeData.xlsx")
$vbLabelText   $csharpLabel

Kod, IronXL'nin esnek hücre adresleme yeteneklerini gösterir. Dize notasyonu ("A1"), Excel kullanıcıları icin dogal gelirken, numerik indeksler donguler ve dinamik oluşturmalar icin programatik kontrol sunar. Aralik atamalari ("B1:B3"), kolonlari ilk işleme koyarken veya varsıyılan degerler uygularken bircok hucresini ayni değer olarak verimli bir sekilde belirler.

IronXL, farklı veri türlerini akıllı bir şekilde işler. Ondalık sayılar, finansal veri hassasiyetini muhafaza eder, DateTime nesneleri Excel tarihleri olarak doğru şekilde biçimlenir ve booleanlar TRUE/FALSE olarak görünür. Bu otomatik dönüştürma, manuel format kodlarini ortadan kaldirirken veri butunlugunu saglar. Buyuk veri setleri icin, ek desenler icin veri aktarma rehberini inceleyin.

Çıktı

C# Kullanarak IronXL ile Excel Dosyası Oluşturma: Görüntü 7 - Excel Çıkışı

Excel Dosyalarina Profesyonel Formatlama Nasıl Uygulanir?

Profesyonel Excel dosyalari sadece ham verilerden daha fazlasini gerektirir. IronXL'nin stil API'si, duz dosyalari bicimlendirme, renkler ve gorunus hiyerarşisiyle guzel is belgelerine dönüştürur. Hucre bicimlendirmesi uygulayarak tablo gorunumunun her yonunu kontrol edebilirsiniz.

using IronXL;
WorkBook workbook = WorkBook.Create(ExcelFileFormat.XLSX);
WorkSheet worksheet = workbook.CreateWorkSheet("Employees");
// Header formatting
var headerRange = worksheet["A1:D1"];
headerRange.Style.Font.Bold = true;
headerRange.Style.Font.Height = 12;
headerRange.Style.SetBackgroundColor("#4472C4");
headerRange.Style.Font.Color = "#FFFFFF";
// Column width adjustment
worksheet.AutoSizeColumn(0); // Auto-fit column A
worksheet.GetColumn(1).Width = 20; // Set column B width
// Number formatting
var salaryColumn = worksheet["E2:E3"];
salaryColumn.FormatString = "$#,##0.00";
// Date formatting
var dateColumn = worksheet["F2:F3"];
dateColumn.FormatString = "MM/dd/yyyy";
// Cell borders
var dataRange = worksheet["A1:G3"];
dataRange.Style.TopBorder.Type = IronXl.Styles.BorderType.Thin;
dataRange.Style.BottomBorder.Type = IronXl.Styles.BorderType.Thin;
dataRange.Style.LeftBorder.Type = IronXl.Styles.BorderType.Thin;
dataRange.Style.RightBorder.Type = IronXl.Styles.BorderType.Thin;
dataRange.Style.TopBorder.Color = "#000000";
dataRange.Style.BottomBorder.Color = "#000000";
// Text alignment
worksheet["A1:G1"].Style.HorizontalAlignment = IronXl.Styles.HorizontalAlignment.Center;
// Alternating row colors for readability (banded rows)
for (int row = 2; row <= 10; row++)
{
    if (row % 2 == 0)
    {
        worksheet[$"A{row}:G{row}"].Style.SetBackgroundColor("#F2F2F2");
    }
}
workbook.SaveAs("FormattedReport.xlsx");
using IronXL;
WorkBook workbook = WorkBook.Create(ExcelFileFormat.XLSX);
WorkSheet worksheet = workbook.CreateWorkSheet("Employees");
// Header formatting
var headerRange = worksheet["A1:D1"];
headerRange.Style.Font.Bold = true;
headerRange.Style.Font.Height = 12;
headerRange.Style.SetBackgroundColor("#4472C4");
headerRange.Style.Font.Color = "#FFFFFF";
// Column width adjustment
worksheet.AutoSizeColumn(0); // Auto-fit column A
worksheet.GetColumn(1).Width = 20; // Set column B width
// Number formatting
var salaryColumn = worksheet["E2:E3"];
salaryColumn.FormatString = "$#,##0.00";
// Date formatting
var dateColumn = worksheet["F2:F3"];
dateColumn.FormatString = "MM/dd/yyyy";
// Cell borders
var dataRange = worksheet["A1:G3"];
dataRange.Style.TopBorder.Type = IronXl.Styles.BorderType.Thin;
dataRange.Style.BottomBorder.Type = IronXl.Styles.BorderType.Thin;
dataRange.Style.LeftBorder.Type = IronXl.Styles.BorderType.Thin;
dataRange.Style.RightBorder.Type = IronXl.Styles.BorderType.Thin;
dataRange.Style.TopBorder.Color = "#000000";
dataRange.Style.BottomBorder.Color = "#000000";
// Text alignment
worksheet["A1:G1"].Style.HorizontalAlignment = IronXl.Styles.HorizontalAlignment.Center;
// Alternating row colors for readability (banded rows)
for (int row = 2; row <= 10; row++)
{
    if (row % 2 == 0)
    {
        worksheet[$"A{row}:G{row}"].Style.SetBackgroundColor("#F2F2F2");
    }
}
workbook.SaveAs("FormattedReport.xlsx");
Imports IronXL

Dim workbook As WorkBook = WorkBook.Create(ExcelFileFormat.XLSX)
Dim worksheet As WorkSheet = workbook.CreateWorkSheet("Employees")

' Header formatting
Dim headerRange = worksheet("A1:D1")
headerRange.Style.Font.Bold = True
headerRange.Style.Font.Height = 12
headerRange.Style.SetBackgroundColor("#4472C4")
headerRange.Style.Font.Color = "#FFFFFF"

' Column width adjustment
worksheet.AutoSizeColumn(0) ' Auto-fit column A
worksheet.GetColumn(1).Width = 20 ' Set column B width

' Number formatting
Dim salaryColumn = worksheet("E2:E3")
salaryColumn.FormatString = "$#,##0.00"

' Date formatting
Dim dateColumn = worksheet("F2:F3")
dateColumn.FormatString = "MM/dd/yyyy"

' Cell borders
Dim dataRange = worksheet("A1:G3")
dataRange.Style.TopBorder.Type = IronXl.Styles.BorderType.Thin
dataRange.Style.BottomBorder.Type = IronXl.Styles.BorderType.Thin
dataRange.Style.LeftBorder.Type = IronXl.Styles.BorderType.Thin
dataRange.Style.RightBorder.Type = IronXl.Styles.BorderType.Thin
dataRange.Style.TopBorder.Color = "#000000"
dataRange.Style.BottomBorder.Color = "#000000"

' Text alignment
worksheet("A1:G1").Style.HorizontalAlignment = IronXl.Styles.HorizontalAlignment.Center

' Alternating row colors for readability (banded rows)
For row As Integer = 2 To 10
    If row Mod 2 = 0 Then
        worksheet($"A{row}:G{row}").Style.SetBackgroundColor("#F2F2F2")
    End If
Next

workbook.SaveAs("FormattedReport.xlsx")
$vbLabelText   $csharpLabel

Görüntülenme standartlarina uygun profesyonel bir gorunum yaratir. Arka plan renkleri ile kalin basliklar gorunus hiyerarşisini saglar. SetBackgroundColor() yöntemi, renk düzeniniz üzerinde hassas kontrol sağlayarak hex renk kodlarını kabul eder. Yazi tipleri, boyut, renk, kalinlik, italik ve alt cizgi seçeneklerini icerir -- bunlarin tamami kurumsal marka kılavuzlarina uygun Excel dosyalari yaratmak icin onemlidir.

Sutun genişliği ayarlamaları, metin kesilmesini onler. AutoSizeColumn() içeriği otomatik olarak sığdırır, GetColumn().Width ise kesin kontrol sağlar. Sayi formatlama, Excel'in format kodlarini kullanir -- ornegin, "$#,##0.00" binlik ayraclar ve iki ondalikli kisim ile para birimi görüntüler. Tarih formatlama benzer desenleri takip eder, Microsoft'un sayi format kodları referansinda aciklandigi gibi standart Excel tarih format dizgelerini kullanarak.

Kenarlar, veri sinirlarini tanimlar, okunabilirligi iyileştirir. BorderType enumu, çeşitli stiller sunar: ince, orta, kalın, noktalı ve kesikli. Sik kullanilan ve "banded rows" olarak adlandırılan, yer değiştiren satır renkleri genis veri setlerinden bilgi takip eden okurlara yardimci olur. Hucre birletirme ve diğer düzen özellikleri hakkında daha fazla bilgi almak icin hucre birletirme rehberini inceleyin.

Çıktı

C# Kullanarak IronXL ile Excel Dosyası Oluşturma: Görüntü 8 - Biçimlendirilmiş Excel Çıkışı

Excel Formüllerini Programatik Olarak Nasıl Kullanirsiniz?

Excel formülleri otomatik hesaplamalar ile hesap tablolarini canlandirir. IronXL, dinamik hesap tabloları oluşturmanızı sağlayan formül yazma ve derecelendirmeyi destekler ve bunları otomatik olarak günceller.

using IronXL;
var workbook = WorkBook.Create();
// Create a budget worksheet
WorkSheet budget = workbook.CreateWorkSheet("Q1 Budget");
// Headers
budget["A1"].Value = "Category";
budget["B1"].Value = "January";
budget["C1"].Value = "February";
budget["D1"].Value = "March";
budget["E1"].Value = "Q1 Total";
// Budget categories and values
string[] categories = { "Salaries", "Marketing", "Operations", "Equipment", "Training" };
decimal[,] monthlyBudgets = {
    { 50000, 52000, 51000 },
    { 15000, 18000, 20000 },
    { 8000, 8500, 9000 },
    { 12000, 5000, 7000 },
    { 3000, 3500, 4000 }
};
// Populate data and add row total formulas
for (int i = 0; i < categories.Length; i++)
{
    budget[$"A{i + 2}"].Value = categories[i];
    budget[$"B{i + 2}"].Value = monthlyBudgets[i, 0];
    budget[$"C{i + 2}"].Value = monthlyBudgets[i, 1];
    budget[$"D{i + 2}"].Value = monthlyBudgets[i, 2];
    budget[$"E{i + 2}"].Formula = $"=SUM(B{i + 2}:D{i + 2})";
}
// Monthly totals row
budget["A7"].Value = "Monthly Total";
budget["B7"].Formula = "=SUM(B2:B6)";
budget["C7"].Formula = "=SUM(C2:C6)";
budget["D7"].Formula = "=SUM(D2:D6)";
budget["E7"].Formula = "=SUM(E2:E6)";
// Calculate percentages
budget["A9"].Value = "Marketing %";
budget["B9"].Formula = "=B3/B7*100";
// Average calculation
budget["A10"].Value = "Average Spending";
budget["B10"].Formula = "=AVERAGE(B2:B6)";
// Evaluate all formulas before saving
workbook.EvaluateAll();
workbook.SaveAs("Budget.xlsx");
using IronXL;
var workbook = WorkBook.Create();
// Create a budget worksheet
WorkSheet budget = workbook.CreateWorkSheet("Q1 Budget");
// Headers
budget["A1"].Value = "Category";
budget["B1"].Value = "January";
budget["C1"].Value = "February";
budget["D1"].Value = "March";
budget["E1"].Value = "Q1 Total";
// Budget categories and values
string[] categories = { "Salaries", "Marketing", "Operations", "Equipment", "Training" };
decimal[,] monthlyBudgets = {
    { 50000, 52000, 51000 },
    { 15000, 18000, 20000 },
    { 8000, 8500, 9000 },
    { 12000, 5000, 7000 },
    { 3000, 3500, 4000 }
};
// Populate data and add row total formulas
for (int i = 0; i < categories.Length; i++)
{
    budget[$"A{i + 2}"].Value = categories[i];
    budget[$"B{i + 2}"].Value = monthlyBudgets[i, 0];
    budget[$"C{i + 2}"].Value = monthlyBudgets[i, 1];
    budget[$"D{i + 2}"].Value = monthlyBudgets[i, 2];
    budget[$"E{i + 2}"].Formula = $"=SUM(B{i + 2}:D{i + 2})";
}
// Monthly totals row
budget["A7"].Value = "Monthly Total";
budget["B7"].Formula = "=SUM(B2:B6)";
budget["C7"].Formula = "=SUM(C2:C6)";
budget["D7"].Formula = "=SUM(D2:D6)";
budget["E7"].Formula = "=SUM(E2:E6)";
// Calculate percentages
budget["A9"].Value = "Marketing %";
budget["B9"].Formula = "=B3/B7*100";
// Average calculation
budget["A10"].Value = "Average Spending";
budget["B10"].Formula = "=AVERAGE(B2:B6)";
// Evaluate all formulas before saving
workbook.EvaluateAll();
workbook.SaveAs("Budget.xlsx");
Imports IronXL

Dim workbook = WorkBook.Create()
' Create a budget worksheet
Dim budget As WorkSheet = workbook.CreateWorkSheet("Q1 Budget")
' Headers
budget("A1").Value = "Category"
budget("B1").Value = "January"
budget("C1").Value = "February"
budget("D1").Value = "March"
budget("E1").Value = "Q1 Total"
' Budget categories and values
Dim categories As String() = {"Salaries", "Marketing", "Operations", "Equipment", "Training"}
Dim monthlyBudgets As Decimal(,) = {
    {50000, 52000, 51000},
    {15000, 18000, 20000},
    {8000, 8500, 9000},
    {12000, 5000, 7000},
    {3000, 3500, 4000}
}
' Populate data and add row total formulas
For i As Integer = 0 To categories.Length - 1
    budget($"A{i + 2}").Value = categories(i)
    budget($"B{i + 2}").Value = monthlyBudgets(i, 0)
    budget($"C{i + 2}").Value = monthlyBudgets(i, 1)
    budget($"D{i + 2}").Value = monthlyBudgets(i, 2)
    budget($"E{i + 2}").Formula = $"=SUM(B{i + 2}:D{i + 2})"
Next
' Monthly totals row
budget("A7").Value = "Monthly Total"
budget("B7").Formula = "=SUM(B2:B6)"
budget("C7").Formula = "=SUM(C2:C6)"
budget("D7").Formula = "=SUM(D2:D6)"
budget("E7").Formula = "=SUM(E2:E6)"
' Calculate percentages
budget("A9").Value = "Marketing %"
budget("B9").Formula = "=B3/B7*100"
' Average calculation
budget("A10").Value = "Average Spending"
budget("B10").Formula = "=AVERAGE(B2:B6)"
' Evaluate all formulas before saving
workbook.EvaluateAll()
workbook.SaveAs("Budget.xlsx")
$vbLabelText   $csharpLabel

Bu butce ornegi, formlarin pratik uygulamasini gösterir. Formula özelliği, bir eşittir işareti ile başlayan standart Excel formül söz dizimini kabul eder. IronXL, SUM, AVERAGE, COUNT, MAX, MIN ve digerleri dahil yaygın fonksiyonlari destekler. Formullerdeki hucre referansları, Excel'deki gibi çalişır, göreceli ve mutlak referanslar dahil olmak üzere.

EvaluateAll() yöntemi, tüm formülleri işler, çalışma kitabı boyunca hesaplanan değerleri günceller. Bu, Excel'de dosya acildiginda formul sonuclarinin görüntülenmesini saglar. Degerlendirme olmadan, Excel, kullanicinin yeniden hesaplama tetikleyene kadar formül metnini gösterir. Formül sonuçlarinin nasıl okunacagi konusunda daha fazla bilgi için Excel dosyasi okuma dokümanini inceleyin.

Çıktı

C# Kullanarak IronXL ile Excel Dosyası Oluşturma: Görüntü 9 - Formüller Kullanılarak Excel Çıkışı

Veritabanı Verisini Excel'e Nasıl Aktarirsiniz?

Gerçek dunya uygulamaları sık sık raporlar ve analizler icin veritabanı verilerini Excel'e aktarır. IronXL, dahili DataTable desteğiyle bu süreci kolaylaştırır, manuel alan eşlemesi ihtiyaçını ortadan kaldırarak C# uygulamalarından Excel'e ihraç ederken.

using System.Data;
using IronXL;

// Simulate database retrieval (replace with actual database code)
DataTable GetSalesData()
{
    DataTable dt = new DataTable("Sales");
    dt.Columns.Add("OrderID", typeof(int));
    dt.Columns.Add("CustomerName", typeof(string));
    dt.Columns.Add("Product", typeof(string));
    dt.Columns.Add("Quantity", typeof(int));
    dt.Columns.Add("UnitPrice", typeof(decimal));
    dt.Columns.Add("OrderDate", typeof(DateTime));
    dt.Rows.Add(1001, "ABC Corp", "Widget Pro", 50, 25.99m, DateTime.Now.AddDays(-5));
    dt.Rows.Add(1002, "XYZ Ltd", "Widget Basic", 100, 15.99m, DateTime.Now.AddDays(-4));
    dt.Rows.Add(1003, "ABC Corp", "Widget Premium", 25, 45.99m, DateTime.Now.AddDays(-3));
    dt.Rows.Add(1004, "Tech Solutions", "Widget Pro", 75, 25.99m, DateTime.Now.AddDays(-2));
    dt.Rows.Add(1005, "XYZ Ltd", "Widget Premium", 30, 45.99m, DateTime.Now.AddDays(-1));
    return dt;
}

// Export to Excel
WorkBook reportWorkbook = WorkBook.Create();
WorkSheet reportSheet = reportWorkbook.CreateWorkSheet("Sales Report");
DataTable salesData = GetSalesData();

// Title row
reportSheet["A1"].Value = "Order Report - " + DateTime.Now.ToString("MMMM yyyy");
reportSheet.Merge("A1:F1");
reportSheet["A1"].Style.Font.Bold = true;
reportSheet["A1"].Style.Font.Height = 14;

// Headers
int headerRow = 3;
for (int col = 0; col < salesData.Columns.Count; col++)
{
    reportSheet.SetCellValue(headerRow - 1, col, salesData.Columns[col].ColumnName);
}
var headers = reportSheet[$"A{headerRow}:F{headerRow}"];
headers.Style.Font.Bold = true;
headers.Style.SetBackgroundColor("#D9E1F2");

// Data rows
for (int row = 0; row < salesData.Rows.Count; row++)
{
    for (int col = 0; col < salesData.Columns.Count; col++)
    {
        reportSheet.SetCellValue(row + headerRow, col, salesData.Rows[row][col]);
    }
    reportSheet[$"G{row + headerRow + 1}"].Formula = $"=D{row + headerRow + 1}*E{row + headerRow + 1}";
}

// Total header
reportSheet["G3"].Value = "Total";
reportSheet["G3"].Style.Font.Bold = true;
reportSheet["G3"].Style.SetBackgroundColor("#D9E1F2");
// Format currency and date columns
reportSheet[$"E{headerRow + 1}:E{headerRow + salesData.Rows.Count}"].FormatString = "$#,##0.00";
reportSheet[$"G{headerRow + 1}:G{headerRow + salesData.Rows.Count}"].FormatString = "$#,##0.00";
reportSheet[$"F{headerRow + 1}:F{headerRow + salesData.Rows.Count}"].FormatString = "MM/dd/yyyy";

// Summary section
int summaryRow = headerRow + salesData.Rows.Count + 2;
reportSheet[$"A{summaryRow}"].Value = "Summary";
reportSheet[$"A{summaryRow}"].Style.Font.Bold = true;
reportSheet[$"A{summaryRow + 1}"].Value = "Total Orders:";
reportSheet[$"B{summaryRow + 1}"].Formula = $"=COUNTA(A{headerRow + 1}:A{headerRow + salesData.Rows.Count})";
reportSheet[$"A{summaryRow + 2}"].Value = "Total Revenue:";
reportSheet[$"B{summaryRow + 2}"].Formula = $"=SUM(G{headerRow + 1}:G{headerRow + salesData.Rows.Count})";
reportSheet[$"B{summaryRow + 2}"].FormatString = "$#,##0.00";

for (int col = 0; col <= 6; col++) { reportSheet.AutoSizeColumn(col); }
reportWorkbook.EvaluateAll();
reportWorkbook.SaveAs("DatabaseExport.xlsx");
using System.Data;
using IronXL;

// Simulate database retrieval (replace with actual database code)
DataTable GetSalesData()
{
    DataTable dt = new DataTable("Sales");
    dt.Columns.Add("OrderID", typeof(int));
    dt.Columns.Add("CustomerName", typeof(string));
    dt.Columns.Add("Product", typeof(string));
    dt.Columns.Add("Quantity", typeof(int));
    dt.Columns.Add("UnitPrice", typeof(decimal));
    dt.Columns.Add("OrderDate", typeof(DateTime));
    dt.Rows.Add(1001, "ABC Corp", "Widget Pro", 50, 25.99m, DateTime.Now.AddDays(-5));
    dt.Rows.Add(1002, "XYZ Ltd", "Widget Basic", 100, 15.99m, DateTime.Now.AddDays(-4));
    dt.Rows.Add(1003, "ABC Corp", "Widget Premium", 25, 45.99m, DateTime.Now.AddDays(-3));
    dt.Rows.Add(1004, "Tech Solutions", "Widget Pro", 75, 25.99m, DateTime.Now.AddDays(-2));
    dt.Rows.Add(1005, "XYZ Ltd", "Widget Premium", 30, 45.99m, DateTime.Now.AddDays(-1));
    return dt;
}

// Export to Excel
WorkBook reportWorkbook = WorkBook.Create();
WorkSheet reportSheet = reportWorkbook.CreateWorkSheet("Sales Report");
DataTable salesData = GetSalesData();

// Title row
reportSheet["A1"].Value = "Order Report - " + DateTime.Now.ToString("MMMM yyyy");
reportSheet.Merge("A1:F1");
reportSheet["A1"].Style.Font.Bold = true;
reportSheet["A1"].Style.Font.Height = 14;

// Headers
int headerRow = 3;
for (int col = 0; col < salesData.Columns.Count; col++)
{
    reportSheet.SetCellValue(headerRow - 1, col, salesData.Columns[col].ColumnName);
}
var headers = reportSheet[$"A{headerRow}:F{headerRow}"];
headers.Style.Font.Bold = true;
headers.Style.SetBackgroundColor("#D9E1F2");

// Data rows
for (int row = 0; row < salesData.Rows.Count; row++)
{
    for (int col = 0; col < salesData.Columns.Count; col++)
    {
        reportSheet.SetCellValue(row + headerRow, col, salesData.Rows[row][col]);
    }
    reportSheet[$"G{row + headerRow + 1}"].Formula = $"=D{row + headerRow + 1}*E{row + headerRow + 1}";
}

// Total header
reportSheet["G3"].Value = "Total";
reportSheet["G3"].Style.Font.Bold = true;
reportSheet["G3"].Style.SetBackgroundColor("#D9E1F2");
// Format currency and date columns
reportSheet[$"E{headerRow + 1}:E{headerRow + salesData.Rows.Count}"].FormatString = "$#,##0.00";
reportSheet[$"G{headerRow + 1}:G{headerRow + salesData.Rows.Count}"].FormatString = "$#,##0.00";
reportSheet[$"F{headerRow + 1}:F{headerRow + salesData.Rows.Count}"].FormatString = "MM/dd/yyyy";

// Summary section
int summaryRow = headerRow + salesData.Rows.Count + 2;
reportSheet[$"A{summaryRow}"].Value = "Summary";
reportSheet[$"A{summaryRow}"].Style.Font.Bold = true;
reportSheet[$"A{summaryRow + 1}"].Value = "Total Orders:";
reportSheet[$"B{summaryRow + 1}"].Formula = $"=COUNTA(A{headerRow + 1}:A{headerRow + salesData.Rows.Count})";
reportSheet[$"A{summaryRow + 2}"].Value = "Total Revenue:";
reportSheet[$"B{summaryRow + 2}"].Formula = $"=SUM(G{headerRow + 1}:G{headerRow + salesData.Rows.Count})";
reportSheet[$"B{summaryRow + 2}"].FormatString = "$#,##0.00";

for (int col = 0; col <= 6; col++) { reportSheet.AutoSizeColumn(col); }
reportWorkbook.EvaluateAll();
reportWorkbook.SaveAs("DatabaseExport.xlsx");
Imports System.Data
Imports IronXL

' Simulate database retrieval (replace with actual database code)
Function GetSalesData() As DataTable
    Dim dt As New DataTable("Sales")
    dt.Columns.Add("OrderID", GetType(Integer))
    dt.Columns.Add("CustomerName", GetType(String))
    dt.Columns.Add("Product", GetType(String))
    dt.Columns.Add("Quantity", GetType(Integer))
    dt.Columns.Add("UnitPrice", GetType(Decimal))
    dt.Columns.Add("OrderDate", GetType(DateTime))
    dt.Rows.Add(1001, "ABC Corp", "Widget Pro", 50, 25.99D, DateTime.Now.AddDays(-5))
    dt.Rows.Add(1002, "XYZ Ltd", "Widget Basic", 100, 15.99D, DateTime.Now.AddDays(-4))
    dt.Rows.Add(1003, "ABC Corp", "Widget Premium", 25, 45.99D, DateTime.Now.AddDays(-3))
    dt.Rows.Add(1004, "Tech Solutions", "Widget Pro", 75, 25.99D, DateTime.Now.AddDays(-2))
    dt.Rows.Add(1005, "XYZ Ltd", "Widget Premium", 30, 45.99D, DateTime.Now.AddDays(-1))
    Return dt
End Function

' Export to Excel
Dim reportWorkbook As WorkBook = WorkBook.Create()
Dim reportSheet As WorkSheet = reportWorkbook.CreateWorkSheet("Sales Report")
Dim salesData As DataTable = GetSalesData()

' Title row
reportSheet("A1").Value = "Order Report - " & DateTime.Now.ToString("MMMM yyyy")
reportSheet.Merge("A1:F1")
reportSheet("A1").Style.Font.Bold = True
reportSheet("A1").Style.Font.Height = 14

' Headers
Dim headerRow As Integer = 3
For col As Integer = 0 To salesData.Columns.Count - 1
    reportSheet.SetCellValue(headerRow - 1, col, salesData.Columns(col).ColumnName)
Next
Dim headers = reportSheet($"A{headerRow}:F{headerRow}")
headers.Style.Font.Bold = True
headers.Style.SetBackgroundColor("#D9E1F2")

' Data rows
For row As Integer = 0 To salesData.Rows.Count - 1
    For col As Integer = 0 To salesData.Columns.Count - 1
        reportSheet.SetCellValue(row + headerRow, col, salesData.Rows(row)(col))
    Next
    reportSheet($"G{row + headerRow + 1}").Formula = $"=D{row + headerRow + 1}*E{row + headerRow + 1}"
Next

' Total header
reportSheet("G3").Value = "Total"
reportSheet("G3").Style.Font.Bold = True
reportSheet("G3").Style.SetBackgroundColor("#D9E1F2")

' Format currency and date columns
reportSheet($"E{headerRow + 1}:E{headerRow + salesData.Rows.Count}").FormatString = "$#,##0.00"
reportSheet($"G{headerRow + 1}:G{headerRow + salesData.Rows.Count}").FormatString = "$#,##0.00"
reportSheet($"F{headerRow + 1}:F{headerRow + salesData.Rows.Count}").FormatString = "MM/dd/yyyy"

' Summary section
Dim summaryRow As Integer = headerRow + salesData.Rows.Count + 2
reportSheet($"A{summaryRow}").Value = "Summary"
reportSheet($"A{summaryRow}").Style.Font.Bold = True
reportSheet($"A{summaryRow + 1}").Value = "Total Orders:"
reportSheet($"B{summaryRow + 1}").Formula = $"=COUNTA(A{headerRow + 1}:A{headerRow + salesData.Rows.Count})"
reportSheet($"A{summaryRow + 2}").Value = "Total Revenue:"
reportSheet($"B{summaryRow + 2}").Formula = $"=SUM(G{headerRow + 1}:G{headerRow + salesData.Rows.Count})"
reportSheet($"B{summaryRow + 2}").FormatString = "$#,##0.00"

For col As Integer = 0 To 6
    reportSheet.AutoSizeColumn(col)
Next
reportWorkbook.EvaluateAll()
reportWorkbook.SaveAs("DatabaseExport.xlsx")
$vbLabelText   $csharpLabel

Bu örnek, tam bir veritabanıdan Excel'e iş akışını gösterir. DataTable, veritabanı alımını simüle eder -- üretimde, bunu Entity Framework, Dapper veya ADO.NET kullanarak gerçek veritabanı sorgularıyla değiştirin. Elle esleme yaklasimi, bicimlendirme ve duzen uzerinde tam kontrol saglar ve Microsoft'un veri aktarma en iyi uygulamalari tarafından önerilir.

Kod, baslik, biçimlendirilmis baslıklar ve veri satirları ile profesyonel bir rapor oluşturur. Formülsütunları, satır toplamlarını dinamik bir şekilde hesaplar. Özet bölümünde, siparişleri saymak ve geliri toplamak için Excel formulleri kullanilir, veri degisirse bu degerlerin güncellendigi görüntülenir. DataSets ve daha buyuk veri yapilariyla calismak icin, Excel to DataSet dönüştürme rehberine bakin.

Çıktı

C# Kullanarak IronXL ile Excel Dosyası Oluşturma: Görüntü 10 - Veritabanından Excel'e İhracat Çıkışı

Excel raporlamasini üretime almaniz mi gerekiyor? Lisans alin ve üretim dağıtımları icin IronXL'nin tam potansiyelini ortaya cikarin.

Birden Çok Calisma Sayfasiyla Nasıl Bas Edersiniz?

Karmaşık Excel dosyaları, ilgili verileri düzenlemek için genellikle birden çok calisma sayfasi gerektirir. IronXL, calisma sayfalarini oluşturmak, erişmek ve düzenlemek icin sezgisel yöntemlerle çok sayfalı yönetimi basitlestirir. Calisma kitabı sayfalarini acip yonetebilir ve sadece birkaç satır kod ile calisabilirsiniz.

using IronXL;
WorkBook companyReport = WorkBook.Create();
// Create department sheets
WorkSheet salesSheet = companyReport.CreateWorkSheet("Sales");
WorkSheet inventorySheet = companyReport.CreateWorkSheet("Inventory");
WorkSheet summarySheet = companyReport.CreateWorkSheet("Summary");

// Populate Sales sheet
salesSheet["A1"].Value = "Sales Dashboard";
salesSheet["A3"].Value = "Region";
salesSheet["B3"].Value = "Q1 Sales";
salesSheet["C3"].Value = "Q2 Sales";
string[] regions = { "North", "South", "East", "West" };
decimal[] q1Sales = { 250000, 180000, 220000, 195000 };
decimal[] q2Sales = { 275000, 195000, 240000, 210000 };
for (int i = 0; i < regions.Length; i++)
{
    salesSheet[$"A{i + 4}"].Value = regions[i];
    salesSheet[$"B{i + 4}"].Value = q1Sales[i];
    salesSheet[$"C{i + 4}"].Value = q2Sales[i];
}

// Populate Inventory sheet
inventorySheet["A1"].Value = "Inventory Status";
string[] products = { "Widget A", "Widget B", "Widget C" };
int[] stock = { 150, 45, 200 };
int[] reorderPoint = { 100, 50, 75 };
for (int i = 0; i < products.Length; i++)
{
    inventorySheet[$"A{i + 4}"].Value = products[i];
    inventorySheet[$"B{i + 4}"].Value = stock[i];
    inventorySheet[$"C{i + 4}"].Value = reorderPoint[i];
    string status = stock[i] <= reorderPoint[i] ? "REORDER" : "OK";
    inventorySheet[$"D{i + 4}"].Value = status;
    if (status == "REORDER")
        inventorySheet[$"D{i + 4}"].Style.Font.Color = "#FF0000";
}

// Summary sheet with cross-sheet formulas
summarySheet["A1"].Value = "Company Overview";
summarySheet["A4"].Value = "Total Q1 Sales";
summarySheet["B4"].Formula = "=SUM(Sales!B4:B7)";
summarySheet["A5"].Value = "Total Q2 Sales";
summarySheet["B5"].Formula = "=SUM(Sales!C4:C7)";
summarySheet["A6"].Value = "Products Need Reorder";
summarySheet["B6"].Formula = "=COUNTIF(Inventory!D4:D6,\"REORDER\")";

// Apply consistent formatting across all sheets
foreach (WorkSheet sheet in companyReport.WorkSheets)
{
    sheet["A1"].Style.Font.Bold = true;
    sheet["A1"].Style.Font.Height = 14;
}
companyReport.SaveAs("CompanyReport.xlsx");
using IronXL;
WorkBook companyReport = WorkBook.Create();
// Create department sheets
WorkSheet salesSheet = companyReport.CreateWorkSheet("Sales");
WorkSheet inventorySheet = companyReport.CreateWorkSheet("Inventory");
WorkSheet summarySheet = companyReport.CreateWorkSheet("Summary");

// Populate Sales sheet
salesSheet["A1"].Value = "Sales Dashboard";
salesSheet["A3"].Value = "Region";
salesSheet["B3"].Value = "Q1 Sales";
salesSheet["C3"].Value = "Q2 Sales";
string[] regions = { "North", "South", "East", "West" };
decimal[] q1Sales = { 250000, 180000, 220000, 195000 };
decimal[] q2Sales = { 275000, 195000, 240000, 210000 };
for (int i = 0; i < regions.Length; i++)
{
    salesSheet[$"A{i + 4}"].Value = regions[i];
    salesSheet[$"B{i + 4}"].Value = q1Sales[i];
    salesSheet[$"C{i + 4}"].Value = q2Sales[i];
}

// Populate Inventory sheet
inventorySheet["A1"].Value = "Inventory Status";
string[] products = { "Widget A", "Widget B", "Widget C" };
int[] stock = { 150, 45, 200 };
int[] reorderPoint = { 100, 50, 75 };
for (int i = 0; i < products.Length; i++)
{
    inventorySheet[$"A{i + 4}"].Value = products[i];
    inventorySheet[$"B{i + 4}"].Value = stock[i];
    inventorySheet[$"C{i + 4}"].Value = reorderPoint[i];
    string status = stock[i] <= reorderPoint[i] ? "REORDER" : "OK";
    inventorySheet[$"D{i + 4}"].Value = status;
    if (status == "REORDER")
        inventorySheet[$"D{i + 4}"].Style.Font.Color = "#FF0000";
}

// Summary sheet with cross-sheet formulas
summarySheet["A1"].Value = "Company Overview";
summarySheet["A4"].Value = "Total Q1 Sales";
summarySheet["B4"].Formula = "=SUM(Sales!B4:B7)";
summarySheet["A5"].Value = "Total Q2 Sales";
summarySheet["B5"].Formula = "=SUM(Sales!C4:C7)";
summarySheet["A6"].Value = "Products Need Reorder";
summarySheet["B6"].Formula = "=COUNTIF(Inventory!D4:D6,\"REORDER\")";

// Apply consistent formatting across all sheets
foreach (WorkSheet sheet in companyReport.WorkSheets)
{
    sheet["A1"].Style.Font.Bold = true;
    sheet["A1"].Style.Font.Height = 14;
}
companyReport.SaveAs("CompanyReport.xlsx");
Imports IronXL

Dim companyReport As WorkBook = WorkBook.Create()
' Create department sheets
Dim salesSheet As WorkSheet = companyReport.CreateWorkSheet("Sales")
Dim inventorySheet As WorkSheet = companyReport.CreateWorkSheet("Inventory")
Dim summarySheet As WorkSheet = companyReport.CreateWorkSheet("Summary")

' Populate Sales sheet
salesSheet("A1").Value = "Sales Dashboard"
salesSheet("A3").Value = "Region"
salesSheet("B3").Value = "Q1 Sales"
salesSheet("C3").Value = "Q2 Sales"
Dim regions As String() = {"North", "South", "East", "West"}
Dim q1Sales As Decimal() = {250000, 180000, 220000, 195000}
Dim q2Sales As Decimal() = {275000, 195000, 240000, 210000}
For i As Integer = 0 To regions.Length - 1
    salesSheet($"A{i + 4}").Value = regions(i)
    salesSheet($"B{i + 4}").Value = q1Sales(i)
    salesSheet($"C{i + 4}").Value = q2Sales(i)
Next

' Populate Inventory sheet
inventorySheet("A1").Value = "Inventory Status"
Dim products As String() = {"Widget A", "Widget B", "Widget C"}
Dim stock As Integer() = {150, 45, 200}
Dim reorderPoint As Integer() = {100, 50, 75}
For i As Integer = 0 To products.Length - 1
    inventorySheet($"A{i + 4}").Value = products(i)
    inventorySheet($"B{i + 4}").Value = stock(i)
    inventorySheet($"C{i + 4}").Value = reorderPoint(i)
    Dim status As String = If(stock(i) <= reorderPoint(i), "REORDER", "OK")
    inventorySheet($"D{i + 4}").Value = status
    If status = "REORDER" Then
        inventorySheet($"D{i + 4}").Style.Font.Color = "#FF0000"
    End If
Next

' Summary sheet with cross-sheet formulas
summarySheet("A1").Value = "Company Overview"
summarySheet("A4").Value = "Total Q1 Sales"
summarySheet("B4").Formula = "=SUM(Sales!B4:B7)"
summarySheet("A5").Value = "Total Q2 Sales"
summarySheet("B5").Formula = "=SUM(Sales!C4:C7)"
summarySheet("A6").Value = "Products Need Reorder"
summarySheet("B6").Formula = "=COUNTIF(Inventory!D4:D6,""REORDER"")"

' Apply consistent formatting across all sheets
For Each sheet As WorkSheet In companyReport.WorkSheets
    sheet("A1").Style.Font.Bold = True
    sheet("A1").Style.Font.Height = 14
Next

companyReport.SaveAs("CompanyReport.xlsx")
$vbLabelText   $csharpLabel

Bu örnek, eksiksiz bir çok sayfalı rapor oluşturur. Her calisma sayfasi belirli bir amaca hizmet eder: satis verileri, envanter takibi ve bir özet gorunumu. Ozet sayfa, önemli metrikleri sayfalar arası formüllerle birleştirir. Sayfa referans sentaksina dikkat edin -- "Sales!B4:B7" Satis sayfasindaki B4 ile B7 hucresine kadar olan alani ifade eder.

Envanter sayfası, düşük stoklu ürünleri kırmızı renkle göstererek koşullu mantığı sergiler. foreach döngüsü, tüm sayfalarda tutarlı biçimlendirme uygular, çalışma kitabı boyunca profesyonel bir görünüm sağlar. Sayfa adları Excel'de sekmeler olarak görünür, kullanıcılara farklı veri görünümleri arasında kolayca gezinme imkanı tanır.

C#'ta Excel Dosyasi Oluşturmanin En Iyi Yöntemleri Nelerdir?

C#'ta verimli Excel dosyası oluşturma, bellek kullanımı, hata yönetimi ve dağıtım konularına düşünceli bir yaklaşımla gerçekleştirilir. Bu uygulamalar, Excel hesap tablolarını programlı bir şekilde oluştururken uygulamalarınızın ölçeklenebilirliğini ve güvenilirliğini korur.

Büyük dosyalarla çalışırken bellek yönetimi kritik hale gelir. Veriyi bir seferde yüklemek yerine parcalara ayirarak isleyin. Asagidaki desen, yuksek hacimli aktarimlar icin bellek kullanimi tahmin edilebilir hale getirir:

using IronXL;
WorkBook workbook = WorkBook.Create();
WorkSheet sheet = workbook.CreateWorkSheet("Data");
int rowsPerBatch = 1000;
int currentRow = 2;
sheet["A1"].Value = "ID";
sheet["B1"].Value = "Name";
sheet["C1"].Value = "Value";
// Process records in manageable batches
foreach (var batch in GetDataInBatches(rowsPerBatch))
{
    foreach (var record in batch)
    {
        sheet[$"A{currentRow}"].Value = record.Id;
        sheet[$"B{currentRow}"].Value = record.Name;
        sheet[$"C{currentRow}"].Value = record.Value;
        currentRow++;
    }
}
workbook.SaveAs("LargeDataset.xlsx");
using IronXL;
WorkBook workbook = WorkBook.Create();
WorkSheet sheet = workbook.CreateWorkSheet("Data");
int rowsPerBatch = 1000;
int currentRow = 2;
sheet["A1"].Value = "ID";
sheet["B1"].Value = "Name";
sheet["C1"].Value = "Value";
// Process records in manageable batches
foreach (var batch in GetDataInBatches(rowsPerBatch))
{
    foreach (var record in batch)
    {
        sheet[$"A{currentRow}"].Value = record.Id;
        sheet[$"B{currentRow}"].Value = record.Name;
        sheet[$"C{currentRow}"].Value = record.Value;
        currentRow++;
    }
}
workbook.SaveAs("LargeDataset.xlsx");
Imports IronXL

Dim workbook As WorkBook = WorkBook.Create()
Dim sheet As WorkSheet = workbook.CreateWorkSheet("Data")
Dim rowsPerBatch As Integer = 1000
Dim currentRow As Integer = 2
sheet("A1").Value = "ID"
sheet("B1").Value = "Name"
sheet("C1").Value = "Value"
' Process records in manageable batches
For Each batch In GetDataInBatches(rowsPerBatch)
    For Each record In batch
        sheet($"A{currentRow}").Value = record.Id
        sheet($"B{currentRow}").Value = record.Name
        sheet($"C{currentRow}").Value = record.Value
        currentRow += 1
    Next
Next
workbook.SaveAs("LargeDataset.xlsx")
$vbLabelText   $csharpLabel

Web uygulamalari icin, Excel dosyalarini bellek icinde oluşturun ve kullanicilara dogrudan akisin yerine, gecici dosyalar yazmak yerine diske akitin. Her zaman oluşturma mantığını hata yonetimi icine alin, böylece çökme ve anlamli geri bildirim saglayin.

// ASP.NET Core controller action with error handling
IActionResult DownloadExcel()
{
    try
    {
        WorkBook workbook = WorkBook.Create();
        WorkSheet sheet = workbook.CreateWorkSheet("Report");
        sheet["A1"].Value = "Report Data";
        // Populate report data here...
        var stream = new MemoryStream();
        workbook.SaveAs(stream);
        stream.Position = 0;
        return File(stream,
            "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
            "report.xlsx");
    }
    catch (Exception ex)
    {
        Console.WriteLine($"Excel generation failed: {ex.Message}");
        return StatusCode(500, "Failed to generate Excel file.");
    }
}
// ASP.NET Core controller action with error handling
IActionResult DownloadExcel()
{
    try
    {
        WorkBook workbook = WorkBook.Create();
        WorkSheet sheet = workbook.CreateWorkSheet("Report");
        sheet["A1"].Value = "Report Data";
        // Populate report data here...
        var stream = new MemoryStream();
        workbook.SaveAs(stream);
        stream.Position = 0;
        return File(stream,
            "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
            "report.xlsx");
    }
    catch (Exception ex)
    {
        Console.WriteLine($"Excel generation failed: {ex.Message}");
        return StatusCode(500, "Failed to generate Excel file.");
    }
}
Imports System
Imports System.IO
Imports Microsoft.AspNetCore.Mvc

Public Class YourController
    Inherits Controller

    Public Function DownloadExcel() As IActionResult
        Try
            Dim workbook As WorkBook = WorkBook.Create()
            Dim sheet As WorkSheet = workbook.CreateWorkSheet("Report")
            sheet("A1").Value = "Report Data"
            ' Populate report data here...
            Dim stream As New MemoryStream()
            workbook.SaveAs(stream)
            stream.Position = 0
            Return File(stream, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "report.xlsx")
        Catch ex As Exception
            Console.WriteLine($"Excel generation failed: {ex.Message}")
            Return StatusCode(500, "Failed to generate Excel file.")
        End Try
    End Function
End Class
$vbLabelText   $csharpLabel

Asagidaki tablo, önemli en iyi Yöntemleri ve ne zaman uygulanacagini ozetler:

C#'ta Excel Oluşturma icin IronXL En Iyi Yöntemler
Senaryo Önerilen Yaklaşım Fayda
Large datasets (>10,000 rows) Parçalı yazmalarla toplu işlem Azaltılmış bellek kullanımı
Web uygulama indirmeleri Geçici dosyalar yerine MemoryStream Disk IO yok, daha hızlı yanıt
Üretim dağıtımı Geçerli IronXL lisans anahtarını ekleyin Oluşturulan dosyalarda filigran yok
Para birimi ve tarihler FormatString özelliğini kullanın Excel'de doğru yerel ayar gösterimi
Dinamik raporlar SaveAs()'den önce EvaluateAll() çağırın Formüller hesaplanmış değerleri gösterir

IronXL, artırılmış izinler olmadan kısıtlı ortamlarda çalışır, bu da onu paylaşılan barındırma ve kapsayıcılaştırılmış dağıtımlar için uygun kılar. IronXL lisans dosyasını dağıtım paketine dahil edin ve uygulamanızın gerekli geçici dosya işlemleri için yazma izinlerine sahip olduğundan emin olun. Ek dağıtım rehberliği için, IronXL özellikler özeti ve tam API dökümantasyonu danışın.

Buradan Nereye Gidebilirsiniz?

IronXL, C#'ta Excel dosyası oluşturmayı karmaşık bir meydan okumadan, sade bir kodlama haline dönüştürür. Çalışma kitapları oluşturmayı, hücreleri doldurmayı, biçimlendirmeyi uygulamayı, formüller kullanmayı, veritabanı verilerini dışa aktarmayı ve birden fazla çalışma sayfasını yönetmeyi öğrendiniz -- bunların hepsini Microsoft Office bağımlılıkları olmadan. Bu teknikler, .NET 10'u hedefleyen Windows, Linux ve bulut platformlarında tutarlı bir şekilde çalışır.

Daha derine inmek için mevcut Excel dosyalarını okuma ve değiştirme konularında IronXL nasıl yapılır kılavuzlarını inceleyin veya üretime başlamak için deneme lisansı sayfasını ziyaret edin. Proje gereksinimlerinize ve ölçeğinize uygun lisanslama seçeneklerini görüntüleyin.

C# Kullanarak IronXL ile Excel Dosyası Oluşturma: Görüntü 11 - Lisanslama

Sıkça Sorulan Sorular

C# kullanarak Excel dosyaları nasıl oluşturabilirim?

Microsoft Office kurulumu veya karmaşık COM Interop gerekmeksizin Excel dosyalarını C#'de oluşturmak için IronXL'yi kullanabilirsiniz, bu da Excel dosyaları oluşturmayı sağlamak için basit bir API sunar.

C#'ta Excel dosyaları ile çalışmak için Microsoft Office gerekli mi?

Hayır, Microsoft Office gerekmez. IronXL, Office bağımsızlıklarına ihtiyaç duymadan C#'de Excel dosyaları oluşturmanıza ve manipüle etmenize olanak tanır.

Geleneksel yöntemler yerine IronXL kullanmanın avantajları nelerdir?

IronXL, Microsoft Office ve karmaşık COM Interop'a gerek kalmaksızın, Excel dosyası oluşturma ve manipülasyonu için anlaşılır bir API sunarak Excel dosyalarını oluşturma sürecini basitleştirir.

Veritabanlarını Excel dosyaları ile entegre edebilir miyim?

Evet, IronXL, veritabanı entegrasyonu gibi ileri düzey işlemleri destekler ve verileri Excel dosyalarına etkin bir şekilde ihraç etmenize olanak tanır.

IronXL ile hangi dosya formatları oluşturulabilir?

IronXL, farklı Excel dosya oluşturma ihtiyaçları için onu çok yönlü hale getiren hem XLS hem de XLSX dosya formatlarını oluşturmanıza olanak tanır.

IronXL, Excel dosyalarında ileri düzey biçimlendirmeyi destekliyor mu?

Evet, IronXL, Excel dosyalarınızın görünümünü ve yapısını özelleştirmenize olanak tanıyan ileri düzey biçimlendirme özelliklerini destekler.

IronXL kullanarak hesap tablosu oluşturmayı otomatikleştirmek mümkün mü?

Evet, IronXL, rapor oluşturma ve veri ihraç etme gibi işlemleri kolaylaştıran hesap tablosu oluşturma otomasyonu için araçlar ve teknikler sunar.

Excel kullanarak .NET uygulamalarında raporları nasıl oluşturabilirim?

IronXL, Excel dosyalarını doğrudan .NET uygulamalarında oluşturarak rapor oluşturmak için kolay bir yol sunar, veri sunumu için güçlü bir çözüm sağlar.

C# ile Excel ile çalışmak için hangi teknikler gereklidir?

IronXL kullanarak C# ile Excel ile çalışmak için gerekli teknikler arasında temel hesap tablosu oluşturma, ileri düzey biçimlendirme ve veritabanı entegrasyonu bulunur.

C# kullanarak IronXL için belgeleri nerede bulabilirim?

IronXL kullanımı için kapsamlı belgeleri İçeren Iron Software web sitesinde bulabilirsiniz; bu dokümanlar, çeşitli kullanım senaryoları için öğreticiler ve örnekler içerir.

Jordi Bardia
Yazılım Mühendisi
Jordi Python, C# ve C++ konularında en yetkin, Iron Software'deki yeteneklerini kullanmadığı zamanlarda; oyun programlıyor. Ürün testi, ürün geliştirme ve araştırma sorumluluklarını paylaşan Jordi, sürekli ürün gelişimine büyük değer katıyor. Çeşitli deneyimleri onu ...
Daha Fazlasını Oku

Iron Destek Ekibi

Haftanın 5 günü, 24 saat çevrimiçiyiz.
Sohbet
E-posta
Beni Ara