CI/CD boru hatlari için .NET CLI ile yukleme (önerilen)
IronXL, geliştiricilerin .NET Core uygulamalarında Microsoft Office'e ihtiyaç duymadan C# koduyla Excel hücrelerini değiştirmelerine olanak tanır. Hücre manipülasyonu, aralık işlemleri ve Windows, Linux ve macOS'ta dağıtımı destekler.
.NET Core Excel Geliştirme İçin IronXL'i Neden Kullanmalısınız?
.NET Core'da Excel ile çalışma, özellikle bulut özsermaye ve konteynerlerde önemli olan modern kurumsal uygulamalar için önemlidir. IronXL kütüphanesi, platformlar arası gereksiz Office kurulumları olmadan çalışabilen kapsamlı Excel işlevselliği sunar. Bu özellik, rapor oluşturmayı otomatikleştiren DevOps mühendisleri için, veri işleme hatları ve CI/CD iş akışları için özellikle değerlidir.
Kapsamlı bir senaryoyu göz önünde bulundurun: ekibinizin çeşitli veri kaynaklarından aylık performans raporları oluşturması, hesaplamalara dayalı olarak belirli hücreleri değiştirmesi ve bu işlevselliği çeşitli ortamlarda Docker konteynerlerinde dağıtması gerekiyor. Geleneksel Excel otomasyonu, her sunucuda Office kurulumları gerektirecek, lisans zorlukları ve dağıtım karmaşıklıkları yaratacaktı. IronXL, her yerde çalışan bir çözü çözümü sağlayarak bu engelleri ortadan kaldırır.
Kütüphane, sıfırdan elektronik tablolar oluşturma, çalışma sayfalarını programatik olarak yönetme ve harici bağımlılıklar olmadan dosya türleri arasında dönüşüm gerçekleştirme konusunda oldukça pratiktir. İster mikro hizmetler, sunucusuz işlevler, ister konteynerleştirilmiş uygulamalar geliştiriyor olun, IronXL modern DevOps iş akışlarına doğal olarak entegre olur.
Bulut-Native Excel İşleme İçin Neden IronXL'i Seçmelisiniz?
Bulut ortamları, hafif ve esnek çözümler talep eder. IronXL, kutuya hazır olarak Docker dağıtımları, Azure İşlevleri ve AWS Lambda destekleyerek sunar. Kütüphanenin mimarisi, yüksek performansı koruyarak kaynak tüketimini minimumda tutar, bu da maliyet açısından etkili bulut operasyonları için kritik önem taşır. Excel ile Interop olmadan çalışabilir, dağıtımları daha temiz ve daha verimli hale getirebilirsiniz.
.NET Core Excel Düzenleme İçin Temel Yetenekler
| Yetenek | Açıklama |
|---|---|
| Çapraz-platform Uyumluluğu | Windows, Linux ve macOS için yerel destek |
| Konteyner içi kullanım için hazır | Docker ve Kubernetes dağıtımları için optimize edilmiştir |
| Bulut native entegrasyon | Sunucusuz platformlarla sorunsuz çalışır |
| Dış bağımlılıklar yok | Office gereksinimi olmadan kendine yeten kütüphane |
| Performans optimize edildi | Büyük ölçekli işlemler için verimli bellek kullanımı |
IronXL Kütüphanesi Nasıl Kurulur
.NET Core projenizde IronXL'i devreye almak sadece dakikalarınızı alır. Kütüphane, standart paket yöneticileri aracılığıyla kullanılabilir ve tüm modern dağıtım senaryolarını destekler. İşte projeye nasıl IronXL ekleyebileceğiniz:
dotnet add package IronXL.Excel
Ya da Visual Studio'da Paket Yöneticisi Konsolu'nu kullanın
Install-Package IronXL.Excel
Belirli sürüm kurulumu için (tekrarlanabilir yapılar için faydalıdır)
dotnet add package IronXL.Excel --version 2024.12.0
Veya, .csproj dosyanıza ekleyerek, bildirimsel paket yönetimi yapın
<PackageReference Include="IronXL.Excel" Version="2024.12.0" />
Üretim İçin Lisanslama Nasıl Yapılandırılır
Kurulumdan sonra, üretim dağıtımları için lisans anahtarınızı yapılandırın. IronXL, tek sunucu uygulamalarından kurumsal genel çözümler için kullanıma uygun esnek lisans seçenekleri sunar. Web uygulamaları için, merkezi yönetim için lisansı web.config'de yapılandırabilirsiniz. Uygulamalarınızı ölçeklendirme için lisans uzantılarını ve ihtiyaçlarınızı büyüdükçe yükseltme seçeneklerini düşünün.
Container Ortamları İçin IronXL Nasıl İyileştirilir
Docker kurulum en iyi uygulamalarına uygun şekilde hizalandığından emin olunmaları gereken optimizasyon stratejilerini düşünün:
# Dockerfile example for IronXL applications
FROM mcr.microsoft.com/dotnet/runtime:6.0-alpine AS base
WORKDIR /app
# Install required dependencies for Excel processing
RUN apk add --no-cache \
icu-libs \
krb5-libs \
libgcc \
libintl \
libssl1.1 \
libstdc++ \
zlib
FROM mcr.microsoft.com/dotnet/sdk:6.0 AS build
WORKDIR /src
COPY ["YourProject.csproj", "./"]
RUN dotnet restore "YourProject.csproj"
COPY . .
RUN dotnet build "YourProject.csproj" -c Release -o /app/build
FROM build AS publish
RUN dotnet publish "YourProject.csproj" -c Release -o /app/publish
FROM base AS final
WORKDIR /app
COPY --from=publish /app/publish .
ENTRYPOINT ["dotnet", "YourProject.dll"]
.NET Core'da Excel Hücrelerini Hızla Modifiye Etme
İşte temel işlevselliği gösteren pratik bir örnek. Bu kod, mevcut bir Excel dosyasının nasıl yükleneceğini ve belirli hücrelerin nasıl düzenleneceğini gösterir:
using IronXL;
using System;
class QuickStartExample
{
static void Main()
{
// Load existing Excel file - supports XLSX, XLS, XLSM, XLTX
WorkBook workBook = WorkBook.Load("sales_report.xlsx");
// Access the default worksheet (usually first sheet)
WorkSheet sheet = workBook.DefaultWorkSheet;
// Modify individual cells with different data types
sheet["A1"].Value = "Q4 Sales Report"; // String value
sheet["B2"].Value = DateTime.Now; // Date value
sheet["C2"].Value = 158750.50; // Numeric value
// Apply formulas for calculations
sheet["D2"].Formula = "=C2*1.15"; // 15% markup
sheet["E2"].Formula = "=D2-C2"; // Profit calculation
// Bulk update a range of cells
sheet["A5:A15"].Value = "Updated by Automation";
// Style the header row
sheet["A1:E1"].Style.Font.Bold = true;
sheet["A1:E1"].Style.BackgroundColor = "#1F4788";
sheet["A1:E1"].Style.Font.Color = "#FFFFFF";
// Save the modified workbook
workBook.SaveAs("sales_report_updated.xlsx");
Console.WriteLine("Excel file updated successfully!");
}
}
using IronXL;
using System;
class QuickStartExample
{
static void Main()
{
// Load existing Excel file - supports XLSX, XLS, XLSM, XLTX
WorkBook workBook = WorkBook.Load("sales_report.xlsx");
// Access the default worksheet (usually first sheet)
WorkSheet sheet = workBook.DefaultWorkSheet;
// Modify individual cells with different data types
sheet["A1"].Value = "Q4 Sales Report"; // String value
sheet["B2"].Value = DateTime.Now; // Date value
sheet["C2"].Value = 158750.50; // Numeric value
// Apply formulas for calculations
sheet["D2"].Formula = "=C2*1.15"; // 15% markup
sheet["E2"].Formula = "=D2-C2"; // Profit calculation
// Bulk update a range of cells
sheet["A5:A15"].Value = "Updated by Automation";
// Style the header row
sheet["A1:E1"].Style.Font.Bold = true;
sheet["A1:E1"].Style.BackgroundColor = "#1F4788";
sheet["A1:E1"].Style.Font.Color = "#FFFFFF";
// Save the modified workbook
workBook.SaveAs("sales_report_updated.xlsx");
Console.WriteLine("Excel file updated successfully!");
}
}
Imports IronXL
Imports System
Class QuickStartExample
Shared Sub Main()
' Load existing Excel file - supports XLSX, XLS, XLSM, XLTX
Dim workBook As WorkBook = WorkBook.Load("sales_report.xlsx")
' Access the default worksheet (usually first sheet)
Dim sheet As WorkSheet = workBook.DefaultWorkSheet
' Modify individual cells with different data types
sheet("A1").Value = "Q4 Sales Report" ' String value
sheet("B2").Value = DateTime.Now ' Date value
sheet("C2").Value = 158750.5 ' Numeric value
' Apply formulas for calculations
sheet("D2").Formula = "=C2*1.15" ' 15% markup
sheet("E2").Formula = "=D2-C2" ' Profit calculation
' Bulk update a range of cells
sheet("A5:A15").Value = "Updated by Automation"
' Style the header row
sheet("A1:E1").Style.Font.Bold = True
sheet("A1:E1").Style.BackgroundColor = "#1F4788"
sheet("A1:E1").Style.Font.Color = "#FFFFFF"
' Save the modified workbook
workBook.SaveAs("sales_report_updated.xlsx")
Console.WriteLine("Excel file updated successfully!")
End Sub
End Class
Bu Desen Neden Otomasyon İçin İdealdir?
Bu model, deterministik olduğu için otomatik iş akışlarında mükemmel çalışır ve kullanıcı etkileşimini gerektirmez. Bu kodu, olaylar veya zamana dayalı programlar tarafından tetiklenen bir konteynerde çalışacak şekilde zamanlayabilirsiniz, bu da onu DevOps otomasyon senaryoları için ideal hale getirir. Excel çalışma sayfalarını açmak ve programatik olarak düzenlemek etkin otomasyon olanakları sağlar.
.NET Core Excel Düzenleme Projesini Başlatmak
Güvenilir bir Excel düzenleme çözümü oluşturmak, uygun proje kurulumu gerektirir. Üretim dağıtımları için en iyi uygulamaları gösteren, hata işleme ve günlük oluşturmayı entegrasyonunu içeren bir komple örnek oluşturalım:
using IronXL;
using System;
using System.IO;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
public class ExcelProcessor
{
private readonly ILogger<ExcelProcessor> _logger;
private readonly string _workingDirectory;
public ExcelProcessor(ILogger<ExcelProcessor> logger, string workingDirectory)
{
_logger = logger;
_workingDirectory = workingDirectory;
}
public async Task ProcessExcelFileAsync(string fileName)
{
try
{
var filePath = Path.Combine(_workingDirectory, fileName);
// Validate file exists
if (!File.Exists(filePath))
{
_logger.LogError($"File not found: {filePath}");
throw new FileNotFoundException("Excel file not found", fileName);
}
// Load workbook with error handling
_logger.LogInformation($"Loading Excel file: {fileName}");
WorkBook workBook = WorkBook.Load(filePath);
// Process each worksheet
foreach (var worksheet in workBook.WorkSheets)
{
_logger.LogInformation($"Processing worksheet: {worksheet.Name}");
await ProcessWorksheetAsync(worksheet);
}
// Save with timestamp for version control
var outputName = $"{Path.GetFileNameWithoutExtension(fileName)}_processed_{DateTime.Now:yyyyMMddHHmmss}.xlsx";
var outputPath = Path.Combine(_workingDirectory, "output", outputName);
// Ensure output directory exists
Directory.CreateDirectory(Path.GetDirectoryName(outputPath));
workBook.SaveAs(outputPath);
_logger.LogInformation($"Saved processed file: {outputName}");
}
catch (Exception ex)
{
_logger.LogError(ex, $"Error processing Excel file: {fileName}");
throw;
}
}
private async Task ProcessWorksheetAsync(WorkSheet worksheet)
{
// Example: Update timestamp in specific cell
var timestampCell = worksheet["A1"];
if (timestampCell.StringValue == "Last Updated:")
{
worksheet["B1"].Value = DateTime.Now;
worksheet["B1"].FormatString = "yyyy-MM-dd HH:mm:ss";
}
// Example: Process data rows asynchronously
await Task.Run(() =>
{
for (int row = 2; row <= worksheet.RowCount; row++)
{
// Skip empty rows
if (worksheet[$"A{row}"].IsEmpty)
continue;
// Apply business logic
var quantity = worksheet[$"B{row}"].IntValue;
var price = worksheet[$"C{row}"].DoubleValue;
worksheet[$"D{row}"].Value = quantity * price;
worksheet[$"E{row}"].Formula = $"=D{row}*0.08"; // Tax calculation
}
});
}
}
using IronXL;
using System;
using System.IO;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
public class ExcelProcessor
{
private readonly ILogger<ExcelProcessor> _logger;
private readonly string _workingDirectory;
public ExcelProcessor(ILogger<ExcelProcessor> logger, string workingDirectory)
{
_logger = logger;
_workingDirectory = workingDirectory;
}
public async Task ProcessExcelFileAsync(string fileName)
{
try
{
var filePath = Path.Combine(_workingDirectory, fileName);
// Validate file exists
if (!File.Exists(filePath))
{
_logger.LogError($"File not found: {filePath}");
throw new FileNotFoundException("Excel file not found", fileName);
}
// Load workbook with error handling
_logger.LogInformation($"Loading Excel file: {fileName}");
WorkBook workBook = WorkBook.Load(filePath);
// Process each worksheet
foreach (var worksheet in workBook.WorkSheets)
{
_logger.LogInformation($"Processing worksheet: {worksheet.Name}");
await ProcessWorksheetAsync(worksheet);
}
// Save with timestamp for version control
var outputName = $"{Path.GetFileNameWithoutExtension(fileName)}_processed_{DateTime.Now:yyyyMMddHHmmss}.xlsx";
var outputPath = Path.Combine(_workingDirectory, "output", outputName);
// Ensure output directory exists
Directory.CreateDirectory(Path.GetDirectoryName(outputPath));
workBook.SaveAs(outputPath);
_logger.LogInformation($"Saved processed file: {outputName}");
}
catch (Exception ex)
{
_logger.LogError(ex, $"Error processing Excel file: {fileName}");
throw;
}
}
private async Task ProcessWorksheetAsync(WorkSheet worksheet)
{
// Example: Update timestamp in specific cell
var timestampCell = worksheet["A1"];
if (timestampCell.StringValue == "Last Updated:")
{
worksheet["B1"].Value = DateTime.Now;
worksheet["B1"].FormatString = "yyyy-MM-dd HH:mm:ss";
}
// Example: Process data rows asynchronously
await Task.Run(() =>
{
for (int row = 2; row <= worksheet.RowCount; row++)
{
// Skip empty rows
if (worksheet[$"A{row}"].IsEmpty)
continue;
// Apply business logic
var quantity = worksheet[$"B{row}"].IntValue;
var price = worksheet[$"C{row}"].DoubleValue;
worksheet[$"D{row}"].Value = quantity * price;
worksheet[$"E{row}"].Formula = $"=D{row}*0.08"; // Tax calculation
}
});
}
}
Imports IronXL
Imports System
Imports System.IO
Imports System.Threading.Tasks
Imports Microsoft.Extensions.Logging
Public Class ExcelProcessor
Private ReadOnly _logger As ILogger(Of ExcelProcessor)
Private ReadOnly _workingDirectory As String
Public Sub New(logger As ILogger(Of ExcelProcessor), workingDirectory As String)
_logger = logger
_workingDirectory = workingDirectory
End Sub
Public Async Function ProcessExcelFileAsync(fileName As String) As Task
Try
Dim filePath = Path.Combine(_workingDirectory, fileName)
' Validate file exists
If Not File.Exists(filePath) Then
_logger.LogError($"File not found: {filePath}")
Throw New FileNotFoundException("Excel file not found", fileName)
End If
' Load workbook with error handling
_logger.LogInformation($"Loading Excel file: {fileName}")
Dim workBook As WorkBook = WorkBook.Load(filePath)
' Process each worksheet
For Each worksheet In workBook.WorkSheets
_logger.LogInformation($"Processing worksheet: {worksheet.Name}")
Await ProcessWorksheetAsync(worksheet)
Next
' Save with timestamp for version control
Dim outputName = $"{Path.GetFileNameWithoutExtension(fileName)}_processed_{DateTime.Now:yyyyMMddHHmmss}.xlsx"
Dim outputPath = Path.Combine(_workingDirectory, "output", outputName)
' Ensure output directory exists
Directory.CreateDirectory(Path.GetDirectoryName(outputPath))
workBook.SaveAs(outputPath)
_logger.LogInformation($"Saved processed file: {outputName}")
Catch ex As Exception
_logger.LogError(ex, $"Error processing Excel file: {fileName}")
Throw
End Try
End Function
Private Async Function ProcessWorksheetAsync(worksheet As WorkSheet) As Task
' Example: Update timestamp in specific cell
Dim timestampCell = worksheet("A1")
If timestampCell.StringValue = "Last Updated:" Then
worksheet("B1").Value = DateTime.Now
worksheet("B1").FormatString = "yyyy-MM-dd HH:mm:ss"
End If
' Example: Process data rows asynchronously
Await Task.Run(Sub()
For row As Integer = 2 To worksheet.RowCount
' Skip empty rows
If worksheet($"A{row}").IsEmpty Then
Continue For
End If
' Apply business logic
Dim quantity = worksheet($"B{row}").IntValue
Dim price = worksheet($"C{row}").DoubleValue
worksheet($"D{row}").Value = quantity * price
worksheet($"E{row}").Formula = $"=D{row}*0.08" ' Tax calculation
Next
End Sub)
End Function
End Class
Hata İşleme İçin En İyi Uygulamalar
Güvenilir hata işleme, üretim dağıtımları için çok önemlidir. Yukarıdaki örnek, konteyner ortamlarında hataları ayıklamalarını sağlayacak günlük entegrasyonunu ve doğru istisna yönetimini göstermektedir, doğrudan çalışma zamanına erişiminiz olmayabilecek yerlerde. Kullanım durumu için güvenlik önlemleri uygulamayı ve dosya boyut limitlerini gözden geçirmeyi düşünün.
Belirli Bir Hücre Değeri Düzenleme
Basit güncellemelerden karmaşık veri dönüştürmelerine kadar hücre değerlerini nasıl değiştireceğimizi keşfedelim. IronXL, çeşitli veri türlerini ve formatlarını desteklerken Excel hücrelerine değer yazmak için sezgisel yöntemler sağlar. Hücreleri kopyalayabilir ve gerekirse hücre içeriklerini temizleyebilirsiniz.
using IronXL;
using System;
using System.Linq;
using System.Collections.Generic;
public class CellEditingExamples
{
public static void DemonstrateVariousCellEdits()
{
WorkBook workBook = WorkBook.Load("data.xlsx");
WorkSheet sheet = workBook.DefaultWorkSheet;
// 1. Simple value assignment
sheet["A1"].Value = "Product Name";
sheet["B1"].Value = 99.99;
sheet["C1"].Value = true;
sheet["D1"].Value = DateTime.Now;
// 2. Using cell references with variables
int rowIndex = 5;
string columnLetter = "E";
sheet[$"{columnLetter}{rowIndex}"].Value = "Dynamic Reference";
// 3. Setting values with specific formatting
sheet["F1"].Value = 0.175;
sheet["F1"].FormatString = "0.00%"; // Display as 17.50%
// 4. Currency formatting
sheet["G1"].Value = 1234.56;
sheet["G1"].FormatString = "$#,##0.00"; // Display as $1,234.56
// 5. Date formatting variations
var dateCell = sheet["H1"];
dateCell.Value = DateTime.Now;
dateCell.FormatString = "MMM dd, yyyy"; // Display as "Dec 25, 2024"
// 6. Setting hyperlinks
sheet["I1"].Value = "Visit Documentation";
sheet["I1"].Hyperlink = "___PROTECTED_URL_54___";
// 7. Applying conditional formatting
foreach (var cell in sheet["J1:J10"])
{
cell.Value = new Random().Next(0, 100);
if (cell.IntValue > 50)
{
cell.Style.BackgroundColor = "#90EE90"; // Light green for high values
}
else
{
cell.Style.BackgroundColor = "#FFB6C1"; // Light red for low values
}
}
// 8. Working with formulas
sheet["K1"].Formula = "=SUM(B1:B10)";
sheet["K2"].Formula = "=AVERAGE(B1:B10)";
sheet["K3"].Formula = "=IF(K2>50,\"Above Average\",\"Below Average\")";
workBook.SaveAs("data_edited.xlsx");
}
}
using IronXL;
using System;
using System.Linq;
using System.Collections.Generic;
public class CellEditingExamples
{
public static void DemonstrateVariousCellEdits()
{
WorkBook workBook = WorkBook.Load("data.xlsx");
WorkSheet sheet = workBook.DefaultWorkSheet;
// 1. Simple value assignment
sheet["A1"].Value = "Product Name";
sheet["B1"].Value = 99.99;
sheet["C1"].Value = true;
sheet["D1"].Value = DateTime.Now;
// 2. Using cell references with variables
int rowIndex = 5;
string columnLetter = "E";
sheet[$"{columnLetter}{rowIndex}"].Value = "Dynamic Reference";
// 3. Setting values with specific formatting
sheet["F1"].Value = 0.175;
sheet["F1"].FormatString = "0.00%"; // Display as 17.50%
// 4. Currency formatting
sheet["G1"].Value = 1234.56;
sheet["G1"].FormatString = "$#,##0.00"; // Display as $1,234.56
// 5. Date formatting variations
var dateCell = sheet["H1"];
dateCell.Value = DateTime.Now;
dateCell.FormatString = "MMM dd, yyyy"; // Display as "Dec 25, 2024"
// 6. Setting hyperlinks
sheet["I1"].Value = "Visit Documentation";
sheet["I1"].Hyperlink = "___PROTECTED_URL_54___";
// 7. Applying conditional formatting
foreach (var cell in sheet["J1:J10"])
{
cell.Value = new Random().Next(0, 100);
if (cell.IntValue > 50)
{
cell.Style.BackgroundColor = "#90EE90"; // Light green for high values
}
else
{
cell.Style.BackgroundColor = "#FFB6C1"; // Light red for low values
}
}
// 8. Working with formulas
sheet["K1"].Formula = "=SUM(B1:B10)";
sheet["K2"].Formula = "=AVERAGE(B1:B10)";
sheet["K3"].Formula = "=IF(K2>50,\"Above Average\",\"Below Average\")";
workBook.SaveAs("data_edited.xlsx");
}
}
Imports IronXL
Imports System
Imports System.Linq
Imports System.Collections.Generic
Public Class CellEditingExamples
Public Shared Sub DemonstrateVariousCellEdits()
Dim workBook As WorkBook = WorkBook.Load("data.xlsx")
Dim sheet As WorkSheet = workBook.DefaultWorkSheet
' 1. Simple value assignment
sheet("A1").Value = "Product Name"
sheet("B1").Value = 99.99
sheet("C1").Value = True
sheet("D1").Value = DateTime.Now
' 2. Using cell references with variables
Dim rowIndex As Integer = 5
Dim columnLetter As String = "E"
sheet($"{columnLetter}{rowIndex}").Value = "Dynamic Reference"
' 3. Setting values with specific formatting
sheet("F1").Value = 0.175
sheet("F1").FormatString = "0.00%" ' Display as 17.50%
' 4. Currency formatting
sheet("G1").Value = 1234.56
sheet("G1").FormatString = "$#,##0.00" ' Display as $1,234.56
' 5. Date formatting variations
Dim dateCell = sheet("H1")
dateCell.Value = DateTime.Now
dateCell.FormatString = "MMM dd, yyyy" ' Display as "Dec 25, 2024"
' 6. Setting hyperlinks
sheet("I1").Value = "Visit Documentation"
sheet("I1").Hyperlink = "___PROTECTED_URL_54___"
' 7. Applying conditional formatting
For Each cell In sheet("J1:J10")
cell.Value = (New Random()).Next(0, 100)
If cell.IntValue > 50 Then
cell.Style.BackgroundColor = "#90EE90" ' Light green for high values
Else
cell.Style.BackgroundColor = "#FFB6C1" ' Light red for low values
End If
Next
' 8. Working with formulas
sheet("K1").Formula = "=SUM(B1:B10)"
sheet("K2").Formula = "=AVERAGE(B1:B10)"
sheet("K3").Formula = "=IF(K2>50,""Above Average"",""Below Average"")"
workBook.SaveAs("data_edited.xlsx")
End Sub
End Class
Farklı Veri Türlerini Etkili Bir Şekilde Ele Alma
IronXL otomatik olarak veri türlerini algılar ve dönüştürür, ancak açık biçimlendirme uygun gösterimi sağlar. Hücre veri formatlarını ayarlamak için kütüphane para birimleri, yüzdeler, tarihler ve özel desenleri destekler. Excel sayı formatlarını gelişmiş biçimlendirme seçenekleri için keşfedebilirsiniz. Ayrıca hücre yazı tiplerini ve boyutlarını özelleştirebilir , arka plan desenleri ve renklerini uygulayabilir ve hücre kenarlarını ve hizalamasını yapılandırabilirsiniz.
Birden Çok Hücreye Değer Atama
Toplu işlemler, etkili Excel işleme için çok önemlidir. IronXL, birden fazla hücreyi aynı anda güncellemeyi kolaylaştıran etkili aralık seçim yetenekleri sağlar. Satır ve sütun ekleyebilir, yeni satır ve sütunlar ekleyebilir ve gerekirse hücreleri birleştirebilirsiniz:
using IronXL;
using System;
using System.Diagnostics;
public class BulkCellOperations
{
public static void PerformBulkUpdates()
{
var stopwatch = Stopwatch.StartNew();
WorkBook workBook = WorkBook.Load("inventory.xlsx");
WorkSheet sheet = workBook.DefaultWorkSheet;
// Method 1: Update entire column
sheet["A:A"].Value = "Updated";
Console.WriteLine($"Column update: {stopwatch.ElapsedMilliseconds}ms");
// Method 2: Update specific range
sheet["B2:B100"].Value = DateTime.Now.ToShortDateString();
// Method 3: Update entire row
sheet["1:1"].Style.Font.Bold = true;
sheet["1:1"].Style.BackgroundColor = "#333333";
sheet["1:1"].Style.Font.Color = "#FFFFFF";
// Method 4: Update rectangular range
sheet["C2:E50"].Formula = "=ROW()*COLUMN()";
// Method 5: Update non-contiguous ranges efficiently
var ranges = new[] { "F1:F10", "H1:H10", "J1:J10" };
foreach (var range in ranges)
{
sheet[range].Value = "Batch Update";
sheet[range].Style.BottomBorder.Type = BorderType.Double;
}
// Method 6: Conditional bulk updates
var dataRange = sheet["K1:K100"];
foreach (var cell in dataRange)
{
// Generate test data
cell.Value = new Random().Next(1, 1000);
// Apply conditional formatting based on value
if (cell.IntValue > 750)
{
cell.Style.BackgroundColor = "#00FF00"; // Green for high values
cell.Style.Font.Bold = true;
}
else if (cell.IntValue < 250)
{
cell.Style.BackgroundColor = "#FF0000"; // Red for low values
cell.Style.Font.Color = "#FFFFFF";
}
}
stopwatch.Stop();
Console.WriteLine($"Total execution time: {stopwatch.ElapsedMilliseconds}ms");
workBook.SaveAs("inventory_bulk_updated.xlsx");
}
}
using IronXL;
using System;
using System.Diagnostics;
public class BulkCellOperations
{
public static void PerformBulkUpdates()
{
var stopwatch = Stopwatch.StartNew();
WorkBook workBook = WorkBook.Load("inventory.xlsx");
WorkSheet sheet = workBook.DefaultWorkSheet;
// Method 1: Update entire column
sheet["A:A"].Value = "Updated";
Console.WriteLine($"Column update: {stopwatch.ElapsedMilliseconds}ms");
// Method 2: Update specific range
sheet["B2:B100"].Value = DateTime.Now.ToShortDateString();
// Method 3: Update entire row
sheet["1:1"].Style.Font.Bold = true;
sheet["1:1"].Style.BackgroundColor = "#333333";
sheet["1:1"].Style.Font.Color = "#FFFFFF";
// Method 4: Update rectangular range
sheet["C2:E50"].Formula = "=ROW()*COLUMN()";
// Method 5: Update non-contiguous ranges efficiently
var ranges = new[] { "F1:F10", "H1:H10", "J1:J10" };
foreach (var range in ranges)
{
sheet[range].Value = "Batch Update";
sheet[range].Style.BottomBorder.Type = BorderType.Double;
}
// Method 6: Conditional bulk updates
var dataRange = sheet["K1:K100"];
foreach (var cell in dataRange)
{
// Generate test data
cell.Value = new Random().Next(1, 1000);
// Apply conditional formatting based on value
if (cell.IntValue > 750)
{
cell.Style.BackgroundColor = "#00FF00"; // Green for high values
cell.Style.Font.Bold = true;
}
else if (cell.IntValue < 250)
{
cell.Style.BackgroundColor = "#FF0000"; // Red for low values
cell.Style.Font.Color = "#FFFFFF";
}
}
stopwatch.Stop();
Console.WriteLine($"Total execution time: {stopwatch.ElapsedMilliseconds}ms");
workBook.SaveAs("inventory_bulk_updated.xlsx");
}
}
Imports IronXL
Imports System
Imports System.Diagnostics
Public Class BulkCellOperations
Public Shared Sub PerformBulkUpdates()
Dim stopwatch = Stopwatch.StartNew()
Dim workBook As WorkBook = WorkBook.Load("inventory.xlsx")
Dim sheet As WorkSheet = workBook.DefaultWorkSheet
' Method 1: Update entire column
sheet("A:A").Value = "Updated"
Console.WriteLine($"Column update: {stopwatch.ElapsedMilliseconds}ms")
' Method 2: Update specific range
sheet("B2:B100").Value = DateTime.Now.ToShortDateString()
' Method 3: Update entire row
sheet("1:1").Style.Font.Bold = True
sheet("1:1").Style.BackgroundColor = "#333333"
sheet("1:1").Style.Font.Color = "#FFFFFF"
' Method 4: Update rectangular range
sheet("C2:E50").Formula = "=ROW()*COLUMN()"
' Method 5: Update non-contiguous ranges efficiently
Dim ranges = {"F1:F10", "H1:H10", "J1:J10"}
For Each range In ranges
sheet(range).Value = "Batch Update"
sheet(range).Style.BottomBorder.Type = BorderType.Double
Next
' Method 6: Conditional bulk updates
Dim dataRange = sheet("K1:K100")
For Each cell In dataRange
' Generate test data
cell.Value = New Random().Next(1, 1000)
' Apply conditional formatting based on value
If cell.IntValue > 750 Then
cell.Style.BackgroundColor = "#00FF00" ' Green for high values
cell.Style.Font.Bold = True
ElseIf cell.IntValue < 250 Then
cell.Style.BackgroundColor = "#FF0000" ' Red for low values
cell.Style.Font.Color = "#FFFFFF"
End If
Next
stopwatch.Stop()
Console.WriteLine($"Total execution time: {stopwatch.ElapsedMilliseconds}ms")
workBook.SaveAs("inventory_bulk_updated.xlsx")
End Sub
End Class
Aralık İşlemlerinin Verimliliği
Aralık işlemleri, bireysel hücreler üzerinden yineleme yerine tek komutlar olarak yürütülür, performansı önemli ölçüde artırır. Bu verimlilik, büyük veri kümeleri işlenirken veya kaynak kısıtlı konteyner ortamlarında çalışılırken kritik hale gelir. Aralıkları seçme ve değiştirme yeteneği, minimum kodla etkili veri dönüşümleri sağlar. Aralıkları sıralayabilir, hücre aralıklarını kırpabilir ve birden fazla aralığı birleştirebilirsiniz.
Yaygın Aralık Seçim Desenleri
| Desen | Söz Dizimi | Açıklama |
|---|---|---|
| Sütun Aralıkları | "A:A" | Tüm sütun A'yı seçer |
| Satır Aralıkları | "1:1" | Tüm satır 1'i seçer |
| Dikdörtgen Aralıklar | "A1:C3" | 3x3 blok seçer |
| Adlandırılmış Aralıklar | Adlandırılmış aralıklar oluşturun ve kullanın | Netlik için |
| Dinamik Aralıklar | Aralık dizelerini programatik olarak oluşturun | Esnek seçim için |
Kullanıcı Girdileriyle Hücreleri Düzenleme
Etkileşimli Excel düzenleme, kullanıcı girdileri veya harici veri kaynakları ile birleştirildiğinde etkili olur. Bu yaklaşım, parametreleri kabul eden ve özel raporlar üreten API'ler oluşturmak için değerlidir. Çeşitli kaynaklardan Excel verilerini içe aktarmak veya farklı formatlara aktarmak isteyebilirsiniz:
using IronXL;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
public class InteractiveExcelEditor
{
public class EditRequest
{
public string FileName { get; set; }
public string WorksheetName { get; set; }
public Dictionary<string, object> CellUpdates { get; set; }
public List<RangeUpdate> RangeUpdates { get; set; }
}
public class RangeUpdate
{
public string Range { get; set; }
public object Value { get; set; }
public CellStyle Style { get; set; }
}
public class CellStyle
{
public string BackgroundColor { get; set; }
public bool Bold { get; set; }
public string NumberFormat { get; set; }
}
public async Task<string> ProcessEditRequestAsync(EditRequest request)
{
try
{
// Load workbook
WorkBook workBook = WorkBook.Load(request.FileName);
WorkSheet sheet = string.IsNullOrEmpty(request.WorksheetName)
? workBook.DefaultWorkSheet
: workBook.GetWorkSheet(request.WorksheetName);
// Process individual cell updates
if (request.CellUpdates != null)
{
foreach (var update in request.CellUpdates)
{
var cell = sheet[update.Key];
cell.Value = update.Value;
// Auto-detect and apply appropriate formatting
if (update.Value is decimal || update.Value is double)
{
cell.FormatString = "#,##0.00";
}
else if (update.Value is DateTime)
{
cell.FormatString = "yyyy-MM-dd";
}
}
}
// Process range updates
if (request.RangeUpdates != null)
{
foreach (var rangeUpdate in request.RangeUpdates)
{
var range = sheet[rangeUpdate.Range];
range.Value = rangeUpdate.Value;
// Apply styling if provided
if (rangeUpdate.Style != null)
{
if (!string.IsNullOrEmpty(rangeUpdate.Style.BackgroundColor))
range.Style.BackgroundColor = rangeUpdate.Style.BackgroundColor;
if (rangeUpdate.Style.Bold)
range.Style.Font.Bold = true;
if (!string.IsNullOrEmpty(rangeUpdate.Style.NumberFormat))
range.FormatString = rangeUpdate.Style.NumberFormat;
}
}
}
// Generate unique output filename
string outputFile = $"edited_{DateTime.Now:yyyyMMddHHmmss}_{request.FileName}";
workBook.SaveAs(outputFile);
return outputFile;
}
catch (Exception ex)
{
throw new InvalidOperationException($"Failed to process edit request: {ex.Message}", ex);
}
}
// Example REST API endpoint implementation
public static async Task<string> HandleApiRequest(string jsonRequest)
{
var request = System.Text.Json.JsonSerializer.Deserialize<EditRequest>(jsonRequest);
var editor = new InteractiveExcelEditor();
return await editor.ProcessEditRequestAsync(request);
}
}
using IronXL;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
public class InteractiveExcelEditor
{
public class EditRequest
{
public string FileName { get; set; }
public string WorksheetName { get; set; }
public Dictionary<string, object> CellUpdates { get; set; }
public List<RangeUpdate> RangeUpdates { get; set; }
}
public class RangeUpdate
{
public string Range { get; set; }
public object Value { get; set; }
public CellStyle Style { get; set; }
}
public class CellStyle
{
public string BackgroundColor { get; set; }
public bool Bold { get; set; }
public string NumberFormat { get; set; }
}
public async Task<string> ProcessEditRequestAsync(EditRequest request)
{
try
{
// Load workbook
WorkBook workBook = WorkBook.Load(request.FileName);
WorkSheet sheet = string.IsNullOrEmpty(request.WorksheetName)
? workBook.DefaultWorkSheet
: workBook.GetWorkSheet(request.WorksheetName);
// Process individual cell updates
if (request.CellUpdates != null)
{
foreach (var update in request.CellUpdates)
{
var cell = sheet[update.Key];
cell.Value = update.Value;
// Auto-detect and apply appropriate formatting
if (update.Value is decimal || update.Value is double)
{
cell.FormatString = "#,##0.00";
}
else if (update.Value is DateTime)
{
cell.FormatString = "yyyy-MM-dd";
}
}
}
// Process range updates
if (request.RangeUpdates != null)
{
foreach (var rangeUpdate in request.RangeUpdates)
{
var range = sheet[rangeUpdate.Range];
range.Value = rangeUpdate.Value;
// Apply styling if provided
if (rangeUpdate.Style != null)
{
if (!string.IsNullOrEmpty(rangeUpdate.Style.BackgroundColor))
range.Style.BackgroundColor = rangeUpdate.Style.BackgroundColor;
if (rangeUpdate.Style.Bold)
range.Style.Font.Bold = true;
if (!string.IsNullOrEmpty(rangeUpdate.Style.NumberFormat))
range.FormatString = rangeUpdate.Style.NumberFormat;
}
}
}
// Generate unique output filename
string outputFile = $"edited_{DateTime.Now:yyyyMMddHHmmss}_{request.FileName}";
workBook.SaveAs(outputFile);
return outputFile;
}
catch (Exception ex)
{
throw new InvalidOperationException($"Failed to process edit request: {ex.Message}", ex);
}
}
// Example REST API endpoint implementation
public static async Task<string> HandleApiRequest(string jsonRequest)
{
var request = System.Text.Json.JsonSerializer.Deserialize<EditRequest>(jsonRequest);
var editor = new InteractiveExcelEditor();
return await editor.ProcessEditRequestAsync(request);
}
}
Imports IronXL
Imports System
Imports System.Collections.Generic
Imports System.Threading.Tasks
Public Class InteractiveExcelEditor
Public Class EditRequest
Public Property FileName As String
Public Property WorksheetName As String
Public Property CellUpdates As Dictionary(Of String, Object)
Public Property RangeUpdates As List(Of RangeUpdate)
End Class
Public Class RangeUpdate
Public Property Range As String
Public Property Value As Object
Public Property Style As CellStyle
End Class
Public Class CellStyle
Public Property BackgroundColor As String
Public Property Bold As Boolean
Public Property NumberFormat As String
End Class
Public Async Function ProcessEditRequestAsync(request As EditRequest) As Task(Of String)
Try
' Load workbook
Dim workBook As WorkBook = WorkBook.Load(request.FileName)
Dim sheet As WorkSheet = If(String.IsNullOrEmpty(request.WorksheetName), workBook.DefaultWorkSheet, workBook.GetWorkSheet(request.WorksheetName))
' Process individual cell updates
If request.CellUpdates IsNot Nothing Then
For Each update In request.CellUpdates
Dim cell = sheet(update.Key)
cell.Value = update.Value
' Auto-detect and apply appropriate formatting
If TypeOf update.Value Is Decimal OrElse TypeOf update.Value Is Double Then
cell.FormatString = "#,##0.00"
ElseIf TypeOf update.Value Is DateTime Then
cell.FormatString = "yyyy-MM-dd"
End If
Next
End If
' Process range updates
If request.RangeUpdates IsNot Nothing Then
For Each rangeUpdate In request.RangeUpdates
Dim range = sheet(rangeUpdate.Range)
range.Value = rangeUpdate.Value
' Apply styling if provided
If rangeUpdate.Style IsNot Nothing Then
If Not String.IsNullOrEmpty(rangeUpdate.Style.BackgroundColor) Then
range.Style.BackgroundColor = rangeUpdate.Style.BackgroundColor
End If
If rangeUpdate.Style.Bold Then
range.Style.Font.Bold = True
End If
If Not String.IsNullOrEmpty(rangeUpdate.Style.NumberFormat) Then
range.FormatString = rangeUpdate.Style.NumberFormat
End If
End If
Next
End If
' Generate unique output filename
Dim outputFile As String = $"edited_{DateTime.Now:yyyyMMddHHmmss}_{request.FileName}"
workBook.SaveAs(outputFile)
Return outputFile
Catch ex As Exception
Throw New InvalidOperationException($"Failed to process edit request: {ex.Message}", ex)
End Try
End Function
' Example REST API endpoint implementation
Public Shared Async Function HandleApiRequest(jsonRequest As String) As Task(Of String)
Dim request = System.Text.Json.JsonSerializer.Deserialize(Of EditRequest)(jsonRequest)
Dim editor = New InteractiveExcelEditor()
Return Await editor.ProcessEditRequestAsync(request)
End Function
End Class
Excel Düzenlemeyi CI/CD Pipeline'larına Entegre Etmek
DevOps senaryoları için, Excel işlemlerini derleme ve dağıtım hatlarınıza entegre edin. Excel dosyalarını ASP.NET uygulamalarında okuyabilir veya gerekirse VB.NET Excel dosyaları ile çalışabilirsiniz:
# Example GitHub Actions workflow
name: Process Excel Reports
on:
schedule:
- cron: '0 2 * * *' # Run daily at 2 AM
workflow_dispatch:
jobs:
process-excel:
runs-on: ubuntu-latest
container:
image: mcr.microsoft.com/dotnet/sdk:6.0
steps:
- uses: actions/checkout@v2
- name: Restore dependencies
run: dotnet restore
- name: Build
run: dotnet build --configuration Release
- name: Process Excel files
run: |
dotnet run -- \
--input-dir ./data/input \
--output-dir ./data/output \
--operation bulk-update
- name: Upload processed files
uses: actions/upload-artifact@v2
with:
name: processed-excel-files
path: ./data/output/*.xlsx
# Example GitHub Actions workflow
name: Process Excel Reports
on:
schedule:
- cron: '0 2 * * *' # Run daily at 2 AM
workflow_dispatch:
jobs:
process-excel:
runs-on: ubuntu-latest
container:
image: mcr.microsoft.com/dotnet/sdk:6.0
steps:
- uses: actions/checkout@v2
- name: Restore dependencies
run: dotnet restore
- name: Build
run: dotnet build --configuration Release
- name: Process Excel files
run: |
dotnet run -- \
--input-dir ./data/input \
--output-dir ./data/output \
--operation bulk-update
- name: Upload processed files
uses: actions/upload-artifact@v2
with:
name: processed-excel-files
path: ./data/output/*.xlsx
Ek Excel Otomasyonu Kaynakları
Excel otomasyon yeteneklerinizi genişletmek için, bu özel kaynakları inceleyin:
Keşfedilecek İleri Düzey Özellikler
IronXL, temel hücre düzenlemenin ötesinde kapsamlı işlevsellik sunar:
- Web tabanlı Excel işlemeleri için Blazor uygulamalarında Excel ile çalışmak
- Daha temiz dağıtımlar için Interop olmadan Excel işlemleri
- .NET'te sıfırdan Excel dosyaları oluşturma
- Veritabanı entegrasyonu için Excel'den SQL'e dönüştürme
- Platformlar arası mobil uygulamalar için .NET MAUI üzerinde Excel ile çalışmak
Excel İşleme İş Akışlarını İyileştirme
Şu gelişmiş teknikleri göz önünde bulundurun:
- Daha zengin raporlar için çalışma sayfalarına resim eklemek
- Daha iyi gezinme için dondurulmuş paneller oluşturmak
- Desenleri vurgulamak için koşullu biçimlendirme uygulayın
- Dinamik hesaplamalar için Excel formüllerini uygulayın
- Belgelenme için hücrelere yorum ekleyin
Excel Düzenleme için Hızlı Referans Kılavuzu
Yaygın Excel düzenleme işlemleri için derlenmiş bir referans:
| İşlem | Kod Örneği | Kullanım Durumu |
|---|---|---|
| Tek Hücre Düzenlemesi | sheet["A1"].Value = "New Value" |
Belirli veri noktalarını güncelleyin |
| Aralık Düzenlemesi | sheet["A1:C10"].Value = "Bulk Update" |
Verimlilik için toplu güncellemeler |
| Formül Uygulaması | sheet["D1"].Formula = "=SUM(A1:C1)" |
Dinamik hesaplamalar |
| Koşullu Biçimlendirme | Değer temelinde renk uygulayın | Görsel veri analizi |
| Tarih Biçimlendirmesi | cell.FormatString = "yyyy-MM-dd" |
Tutarlı tarih gösterimi |
| Para Birimi Formatı | cell.FormatString = "$#,##0.00" |
Finansal raporlama |
| Hücreleri Birleştir | sheet["A1:C1"].Merge() |
Başlık ve alt başlıklar oluştur |
| Otomatik Sütun Boyutlandırma | sheet.AutoSizeColumn(0) |
Okunabilirliği artır |
Bu kapsamlı kılavuz, .NET Core ortamlarında IronXL'in Excel otomasyonunu nasıl basitleştirdiğini gösterir. İster mikroservisler oluşturuyor, konteynerlara dağıtıyor veya sunucusuz fonksiyonlar oluşturuyor olun, IronXL, harici bağımlılıklar olmadan verimli Excel işlemleri için gerekli araçları sağlar. DevOps iş akışlarınızda bu kalıpları bugün uygulamaya başlayarak rapor oluşturma ve veri işleme görevlerini basitleştirin.
Sıkça Sorulan Sorular
.NET Core uygulamalarında Excel kullanmanın amacı nedir?
Excel, verimli veri yönetimi ve manipülasyonu için .NET Core uygulamalarında kullanılır. IronXL, program tarafından Excel dosyalarını yüklemeyi, düzenlemeyi ve kaydetmeyi C# kullanarak sağlar, böylece verimliliği ve veri işleme yeteneklerini artırır.
.NET Core projesine Excel kütüphanesini nasıl yükleyebilirim?
IronXL kütüphanesini .NET Core projesine NuGet Paket Yöneticisi ile dotnet add package IronXL.Excel komutunu kullanarak yükleyebilirsiniz. Alternatif olarak, DLL dosyasını IronXL web sitesinden doğrudan indirebilirsiniz.
.NET Core'da Excel dosyasını yüklemenin adımları nelerdir?
IronXL kullanarak .NET Core'da bir Excel dosyasını yüklemek için WorkBook.Load yöntemini kullanın. Örneğin, WorkBook wb = WorkBook.Load("sample.xlsx"); ifadesi 'sample.xlsx' adlı Excel çalışma kitabını yükleyecektir.
.NET Core kullanarak bir Excel sayfasında bir hücre aralığını düzenleyebilir miyim?
Evet, IronXL ile bir Excel sayfasında bir hücre aralığını aynı anda düzenleyebilirsiniz. ws["A1:A9"].Value = "yeni değer"; sözdizimini, ws bir WorkSheet nesnesi olmak üzere, birden fazla hücreye değer atamak için kullanın.
.NET Core'da Excel dosyalarını düzenlerken kullanıcı girdilerini nasıl işleyebilirim?
IronXL, kullanıcı girdilerini konsol veya bir kullanıcı arayüzü aracılığıyla yakalayarak işleme olanağı sunar. Bu girdiler, Excel tablosunda güncellemeler için hücre aralığını ve değeri tanımlamak için kullanılabilir.
.NET Core'da Excel manipülasyonu için hangi programlama dili kullanılır?
IronXL kütüphanesi kullanılarak .NET Core uygulamalarında Excel dosyalarını programatik olarak manipüle etmek için C# kullanılır.
.NET Core'da Excel dosyalarıyla çalışmak için bir eğitim mevcut mu?
Evet, IronXL ile C# kullanarak Excel dosyalarını okumak ve manipüle etmek üzerine kapsamlı öğretici dersler bulunmaktadır. Ek kaynaklar ve örnek projeler IronXL web sitesinde bulunabilir.
.NET Core'da Excel kütüphanesini kullanmak için uyumluluk gereksinimleri nelerdir?
IronXL, .NET Core'un çeşitli sürümlerini destekler. Ayrıntılı uyumluluk bilgileri IronXL web sitesinde yer alan dokümantasyonda bulunabilir.
Excel kütüphanesinin API dokümantasyonuna nereden erişebilirim?
IronXL'nin API dokümantasyonu, tüm ad alanları, yöntemler ve özellikler hakkında detayları sunarak çevrimiçi olarak mevcuttur. Bu kaynağa erişmek için IronXL web sitesini ziyaret edin.




