CI/CD boru hatlari için .NET CLI ile yukleme (önerilen)
IronXL, geliştiricilerin Microsoft Office'e ihtiyaç duymadan Excel hücrelerini .NET Core uygulamalarında değiştirmelerini sağlar. Hücre manipülasyonu, aralık işlemleri ve Windows, Linux ve macOS'ta dağıtımı destekler.
.NET Core Excel Geliştirme için Neden IronXL Kullanılmalı?
.NET Core'da Excel ile çalışma, özellikle bulut yerel ve konteyner tabanlı ortamlarda modern kurumsal uygulamalar için çok önemlidir. IronXL kütüphanesi, platformlar arası sorunsuz çalışan ve Microsoft Office kurulumlarına ihtiyaç duymayan geniş Excel işlevleri sunar. Bu özellik, rapor üretimini otomatikleştiren DevOps mühendisleri, veri işleme hatları ve CI/CD iş akışları için özellikle değerlidir.
Tipik bir senaryo düşünün: ekibiniz, çeşitli veri kaynaklarından aylık performans raporları üretmeli, hesaplamalara dayanarak belirli hücreleri değiştirmeli ve bu işlevselliği birçok ortamda Docker konteynerleri içinde dağıtmalı. Geleneksel Excel otomasyonu, her sunucuya Office kurulumları gerektirecek, bu da lisanslama sıkıntılar ve dağıtım karmaşıklıkları yaratacaktır. IronXL, .NET Core uygulamalarınızın çalıştığı her yerde çalışan kendi kendine yeten bir çö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 dosya formatları arasında dönüştürme konularında mükemmeldir. Mikro hizmetler, sunucusuz fonksiyonlar veya konteynerleştirilmiş uygulamalar inşa ediyor olun, IronXL modern DevOps iş akışlarına doğal olarak entegre olur.
Bulut Yerel Excel İşleme için Neden IronXL Seçilmeli?
Bulut ortamları hafif ve esnek çözümler talep eder. IronXL, kutudan çıktığı haliyle Docker dağıtımları, Azure Functions ve AWS Lambda destekler. Kutuphanenin mimarisi kaynak tüketimini minimize ederken yüksek performansı korur, bu da maliyet açısından etkili bulut operasyonları için hayati öneme sahiptir. Interop olmadan Excel ile çalışabilir, dağıtımları daha temiz ve verimli hale getirebilirsiniz.
.NET Core Excel Düzenleme için Ana Yetkinlikler
| Yetenek | Tanım |
|---|---|
| Çapraz platform uyumluluğu | Windows, Linux ve macOS için yerel destek |
| Container'e hazır | Docker ve Kubernetes dağıtımları için optimize edilmiştir |
| Bulut yerel entegrasyon | Sunucusuz platformlarla sorunsuz çalışır |
| Harici bağımlılık yok | Office gereksinimi olmadan kendi kendine yeterli kütüphane |
| Performans optimizasyonu | Büyük ölçekli işlemler için etkin bellek kullanımı |
IronXL Kütüphanesi Nasıl Kurulur
.NET Core projenizde IronXL ile başlamanız sadece birkaç dakika alır. Kütüphane standart paket yöneticileri aracılığıyla sağlanır ve tüm modern dağıtım senaryolarını destekler. İşte IronXL'i projenize nasıl ekleyeceğiniz:
dotnet add package IronXl.Excel
# Or use Package Manager Console in Visual Studio
Install-Package IronXl.Excel
# For specific version installation (useful for reproducible builds)
dotnet add package IronXl.Excel --version 2024.12.0
# Add to your .csproj file for declarative package management
# <PackageReference Include="IronXl.Excel" Version="2024.12.0" />
dotnet add package IronXl.Excel
# Or use Package Manager Console in Visual Studio
Install-Package IronXl.Excel
# For specific version installation (useful for reproducible builds)
dotnet add package IronXl.Excel --version 2024.12.0
# Add to your .csproj file for declarative package management
# <PackageReference Include="IronXl.Excel" Version="2024.12.0" />
Üretim için Lisansların Yapılandırılması
Kurulumdan sonra üretim dağıtımları için lisans anahtarınızı yapılandırın. IronXL, tek sunuculu uygulamalardan kurumsal geniş çözümlere kadar farklı dağıtım ölçeklerine uygun esnek lisans seçenekleri sunar. Web uygulamaları için, merkezi yönetim için lisansı web.config içinde yapılandırabilirsiniz. Uygulamalarınızı ölçeklendirmek için lisans uzantılarını ve ihtiyaçlarınız büyüdükçe yükseltme seçeneklerini göz önünde bulundurun.
Konteyner Ortamları için IronXL İyileştirme
Konteynerlara dağıtırken, Docker kurulum en iyi uygulamaları ile uyumlu bu optimizasyon stratejilerini değerlendirin:
# 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ızlıca Değiştirme
İşte temel işlevselliği gösteren pratik bir örnek. Bu kod, mevcut bir Excel dosyasını nasıl yükleyeceğinizi ve belirli hücreleri nasıl değiştireceğinizi gösteriyor:
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 için İdeal?
Bu desen, kararlı bir şekilde çalışarak otomatik iş akışlarına mükemmel uyum sağlar ve kullanıcı etkileşimi gerektirmez. Bu kodu bir konteynerde, olaylar veya zamana bağlı programlar tarafından tetiklenecek şekilde planlayabilirsiniz ve bu, DevOps otomasyon senaryoları için idealdir. Excel çalışma sayfalarını açma ve programatik olarak düzenleme yeteneği etkili otomasyon olanakları sağlar.
.NET Core'da Excel Düzenleme Projesine Başlama
Güvenilir bir Excel düzenleme çözümü oluşturmak doğru proje kurulumunu gerektirir. Üretim dağıtımları için en iyi uygulamaları gösteren, hata yönetimi ve kayıt tutma dahil tam bir ö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 Yönetimi için En İyi Uygulamalar
Üretim dağıtımları için güvenilir hata yönetimi çok önemlidir. Yukarıdaki örnek, günlüğe kaydetme entegrasyonu ve uygun istisna yönetimini gösterir ki bunlar, çalışma zamanına doğrudan erişemeyebileceğiniz konteyner ortamlarında sorun giderme için gereklidir. Kullanım durumunuz için güvenlik önlemleri uygulamayı ve dosya boyutu sınırlarını gözden geçirmeyi düşünün.
Belirli Bir Hücre Değerini Düzenleme
Basit güncellemelerden karmaşık veri dönüşümlerine kadar hücre değerlerini değiştirmek için farklı teknikleri inceleyelim. IronXL, çeşitli veri türlerini ve formatlarını desteklerken Excel hücrelerine değer yazmak için sezgisel yöntemler sağlar. Ayrıca hücreleri kopyalayabilir ve gerektiğinde hücre içeriğini 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 Etkin Bir Şekilde Yönetme
IronXL veri türlerini otomatik olarak algılar ve dönüştürür, ancak açık formatlama uygun görüntülemeyi garanti eder. Kütuphane, para birimleri, yüzdeler, tarihler ve özel desenler için hücre veri formatlarını ayarlamayı destekler. İleri düzey formatlama seçenekleri için Excel numara formatlarını keşfedebilirsiniz. Ayrıca hücre yazı tiplerini ve boyutlarını özelleştirebilir, arka plan desenleri ve renkleri uygulayabilir ve hücre kenarları ve hizalamasını yapılandırabilirsiniz.
Birden Fazla Hücreye Değer Atama
Toplu işlemler, verimli Excel işleme için önemlidir. IronXL, birden çok hücreyi aynı anda güncellemeyi kolaylaştıran etkili aralık seçme yetenekleri sağlar. Ayrıca, gerektiğinde satır ve sütun ekleyebilir, yeni satır ve sütunlar ekleyebilir ve 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 Etkinliği
Aralık işlemleri, tek tek hücreler üzerinden yineleme yapmamaktan ziyade, tek bir komut olarak yürütülür ve performansı önemli ölçüde artırır. Bu etkinlik, büyük veri setlerini işlerken veya kaynak sınırlı konteyner ortamlarında çalışırken hayati önem kazanır. Aralıkları seçme ve manipüle etme yeteneği minimum kodla etkili veri dönüşümlerini sağlar. Ayrıca hücre aralıklarını sıralayabilir, hücre aralıklarını kırpabilir ve birden fazla aralığı birleştirebilirsiniz.
Yaygın Aralık Seçimi Desenleri
| Desen | Sözdizimi | Tanım |
|---|---|---|
| Sütun aralıkları | "A:A" | Tüm A sütununu seçer |
| Satır aralıkları | "1:1" | Tüm 1. satırı seçer |
| Dikdörtgen aralıklar | "A1:C3" | 3x3 bir bloğu seçer |
| Adlandırılmış aralıklar | Adlandırılmış aralıklar oluşturun ve kullanın | Açıklık için |
| Dinamik aralıklar | Aralık dizgilerini programatik olarak oluşturun | Esnek seçim için |
Kullanıcı Girdileri ile Hücre Düzenleme
Etkileşimli Excel düzenleme, kullanıcı girdileri veya harici veri kaynakları ile kombin edildiğinde etkili hale gelir. Bu yaklaşım, parametreleri kabul eden ve özelleştirilmiş raporlar oluşturan API'ler oluşturmak için değerlidir. Farklı kaynaklardan Excel verilerini içe aktarmak veya farklı formatlara dışa 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 İletim Hatlarıyla Entegre Etme
DevOps senaryoları için, Excel işlemlerini inşa ve dağıtım hatlarınıza entegre edin. ASP.NET uygulamalarında Excel dosyalarını okuyabilir veya gerekirse VB.NET Excel dosyalarıyla ç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 Otomasyon Kaynakları
Excel otomasyon yeteneklerinizi genişletmek için bu özel kaynakları keşfedin:
Keşfedilecek İleri Düzey Özellikler
IronXL, temel hücre düzenlemenin ötesinde kapsamlı işlevsellik sunar:
- Blazor uygulamalarında Excel ile çalışma web tabanlı Excel işleme için
- Daha temiz dağıtımlar için Interop olmadan Excel işlemleri
- Sıfırdan .NET'te Excel dosyaları oluşturma
- Veritabanı entegrasyonu için Excel'den SQL'e dönüşüm
- Platformlar arası mobil uygulamalar için .NET MAUI üzerinde Excel ile çalışma
Excel İşleme İş Akışlarını İyileştirme
Bu gelişmiş teknikleri düşünün:
- Daha zengin raporlar için çalışma sayfalarına resim ekleyin
- Daha iyi gezinme için donma panelleri oluşturun
- Kalıpları vurgulamak için koşullu biçimlendirme uygulayın
- Dinamik hesaplamalar için Excel formülleri uygulayın
- Belgelenme için hücrelere yorum ekleyin
Excel Düzenleme için Hızlı Referans Kılavuzu
İşte yaygın Excel düzenleme işlemleri için derlenmiş bir referans:
| İşlem | Kod Örneği | Kullanim Durumu |
|---|---|---|
| Tek Hücre Düzenleme | sheet["A1"].Value = "New Value" |
Belirli veri noktalarını güncelleme |
| Aralık Düzenleme | sheet["A1:C10"].Value = "Bulk Update" |
Verimlilik için toplu güncellemeler |
| Formül Uygulama | sheet["D1"].Formula = "=SUM(A1:C1)" |
Dinamik hesaplamalar |
| Koşullu Biçimlendirme | Değere dayalı renk uygulama | Görsel veri analizi |
| Tarih Biçimlendirme | cell.FormatString = "yyyy-MM-dd" |
Tutarlı tarih gösterimi |
| Para Birimi Biçimi | cell.FormatString = "$#,##0.00" |
Finansal raporlama |
| Hücreleri Birleştirme | sheet["A1:C1"].Merge() |
Başlıklar ve başlıklar oluşturma |
| Sütunları Otomatik Boyutlandırma | sheet.AutoSizeColumn(0) |
Okunabilirliği artırma |
Bu kapsamlı kılavuz, IronXL'nin .NET Core ortamlarında Excel otomasyonunu nasıl basitleştirdiğini gösterir. Mikro hizmetler inşa ediyor, kapsayıcılara dağıtımlar yapıyor veya sunucusuz fonksiyonlar oluşturuyor olun, IronXL harici bağımlılıklara ihtiyaç duymadan verimli Excel işlemleri için gereken araçları sağlar. Bu desenleri bugünden itibaren DevOps iş akışlarınıza uygulamaya başlayarak rapor üretimi ve veri işleme görevlerini basitleştirin.
Sıkça Sorulan Sorular
.NET Core uygulamalarında Excel kullanmanın amacı nedir?
Excel, .NET Core uygulamalarında verimli veri yönetimi ve manipülasyonu için kullanılır. IronXL, geliştiricilerin Excel dosyalarını programatik olarak C# kullanarak yüklemelerini, düzenlemelerini ve kaydetmelerini sağlar, üretkenliği ve veri işleme yeteneklerini artırır.
.NET Core projesinde Excel kütüphanesini nasıl kurabilirim?
NuGet Paket Yöneticisi ile dotnet add package IronXl.Excel komutunu kullanarak IronXL kütüphanesini .NET Core projesine kurabilirsiniz. Alternatif olarak, IronXL web sitesinden doğrudan DLL dosyasını indirebilirsiniz.
.NET Core'da bir Excel dosyası yüklemek için adımlar nelerdir?
IronXL kullanarak .NET Core'da bir Excel dosyası yüklemek için WorkBook.Load yöntemini kullanın. Örneğin, WorkBook wb = WorkBook.Load("sample.xlsx"); 'sample.xlsx' adlı Excel çalışma kitabını yükler.
.NET Core kullanarak bir Excel sayfasında bir hücre aralığını düzenleyebilir miyim?
Evet, IronXL ile bir hücre aralığını aynı anda düzenleyebilirsiniz. ws["A1:A9"].Value = "yeni değer"; söz dizimini kullanarak birden fazla hücreye değer atayın, burada ws bir WorkSheet nesnesidir.
.NET Core'da Excel dosyaları düzenlerken kullanıcı girişlerini nasıl işlerim?
IronXL, kullanıcı girişlerini konsol veya kullanıcı arayüzü aracılığıyla yakalayarak tanımlanan hücre aralığı ve güncellemeler için değer olarak kullanılabilecek harici verileri işlemeye izin verir.
.NET Core'da Excel manipülasyonu için hangi programlama dili kullanılır?
C#, IronXL kütüphanesini kullanarak .NET Core uygulamalarında Excel dosyalarını programatik olarak manipüle etmek için kullanılır.
.NET Core'da Excel dosyaları ile çalışmak için bir eğitim var mı?
Evet, IronXL ile C# kullanarak Excel dosyalarını okuma ve düzenleme konusunda kapsamlı eğitimler mevcuttur. IronXL web sitesinde ek kaynaklar ve örnek projeler bulunabilir.
.NET Core'da Excel kütüphanesini kullanmanın uyumluluk gereksinimleri nedir?
IronXL, çeşitli .NET Core sürümlerini destekler. Ayrıntılı uyumluluk bilgileri, IronXL dokümantasyonunda IronXL web sitesinde bulunabilir.
Excel kütüphanesi için API dokümantasyonuna nereden erişebilirim?
IronXL için API dokümantasyonu, çevrimiçi olarak tüm ad alanları, yöntemler ve özellikler hakkında detaylar sunar. Bu kaynağa erişim için IronXL web sitesini ziyaret edin.




