Infragistics Blazor Excel Library를 사용하면 Workbook, Worksheet, Cell, Formula 등과 같은 익숙한 Microsoft® Excel® 스프레드시트 개체를 사용하여 스프레드시트 데이터로 작업할 수 있습니다. Infragistics Blazor Excel Library를 사용하면 Excel 스프레드시트에서 애플리케이션의 데이터를 쉽게 표현하고 Excel에서 애플리케이션으로 데이터를 전송할 수 있습니다.
using System;
using System.Net.Http;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Text;
using Microsoft.AspNetCore.Components.WebAssembly.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
namespaceInfragistics.Samples
{
publicclassProgram
{
publicstaticasync Task Main(string[] args)
{
var builder = WebAssemblyHostBuilder.CreateDefault(args);
builder.RootComponents.Add<App>("app");
builder.Services.AddScoped(sp => new HttpClient { BaseAddress = new Uri(builder.HostEnvironment.BaseAddress) });
await builder.Build().RunAsync();
}
}
}cs
@using Microsoft.AspNetCore.Components@using Microsoft.AspNetCore.Components.Rendering@using Microsoft.AspNetCore.Components.Forms@using Microsoft.AspNetCore.Components.RenderTree@using Microsoft.AspNetCore.Components.Web@using System.Text.RegularExpressions@using System.Net.Http@using System.Net.Http.Json@using Microsoft.AspNetCore.Components.Routing@using Microsoft.AspNetCore.Components.WebAssembly.Http@using Microsoft.JSInterop@using Microsoft.JSInterop.WebAssembly@using Infragistics.Documents.Excel@using System.Runtime.InteropServices.JavaScript@implements IDisposable
<divclass="container vertical"><divclass="options vertical"><button @onclick="CreateXlsx">Save Workbook to XLSX</button><button @onclick="CreateXls">Save Workbook to XLS</button></div></div>@code {
[Inject]
public IJSRuntime Runtime { get; set; }
publicbool canSave = false;
public Workbook wb;
public Worksheet ws;
public List<string> worksheetRegion = null;
publicstring selectedRegion = null;
private Random Rand = new Random();
protectedoverridevoidOnInitialized()
{
this.WorkbookCreate();
}
privatevoidCreateXls()
{
this.SaveFile(this.wb, "ExcelWorkbook", WorkbookFormat.Excel97To2003);
}
privatevoidCreateXlsx()
{
this.SaveFile(this.wb, "ExcelWorkbook", WorkbookFormat.Excel2007);
}
publicvoidWorkbookCreate() {
Workbook.InProcessRuntime = this.Runtime as IJSInProcessRuntime;
var wb = new Workbook(WorkbookFormat.Excel2007);
var employeeSheet = wb.Worksheets.Add("Employees");
var employeeHeader = employeeSheet.Rows[0];
var companies = newstring[] { "Amazon", "Ford", "Jaguar", "Tesla", "IBM", "Microsoft" };
var firstNames = newstring[] { "Andrew", "Mike", "Martin", "Ann", "Victoria", "John", "Brian", "Jason", "David" };
var lastNames = newstring[] { "Smith", "Jordan", "Johnson", "Anderson", "Louis", "Phillips", "Williams" };
var countries = newstring[] { "UK", "France", "USA", "Germany", "Poland", "Brazil" };
var titles = newstring[] { "Sales Rep.", "Engineer", "Administrator", "Manager" };
var employeeColumns = newstring[] { "Name", "Company", "Title", "Age", "Country" };
for (var col = 0; col < employeeColumns.Length; col++) {
employeeSheet.Columns[col].Width = 5000;
employeeHeader.SetCellValue(col, employeeColumns[col]);
}
for (var i = 1; i < 20; i++) {
var company = this.GetItem(companies);
var title = this.GetItem(titles);
var country = this.GetItem(countries);
var name = this.GetItem(firstNames) + " " + this.GetItem(lastNames);
var salary = this.GetRandom(45000, 95000);
var age = this.GetRandom(20, 65);
var wr = employeeSheet.Rows[i] as WorksheetRow;
wr.SetCellValue(0, name);
wr.SetCellValue(1, company);
wr.SetCellValue(2, title);
wr.SetCellValue(3, age);
wr.SetCellValue(4, country);
wr.SetCellValue(5, salary);
}
var expanseSheet = wb.Worksheets.Add("Expanses");
var expanseHeader = expanseSheet.Rows[0];
var expanseNames = newstring[] { "Year", "Computers", "Research", "Travel", "Salary", "Software" };
var expanseCol = 0;
foreach (var key in expanseNames) {
expanseSheet.Columns[expanseCol].Width = 5000;
expanseHeader.SetCellValue(expanseCol, key);
for (var i = 1; i < 20; i++) {
var wr = expanseSheet.Rows[i];
if (key == "Year") {
wr.SetCellValue(expanseCol, 2010 + i);
} elseif (key == "Computers") {
wr.SetCellValue(expanseCol, this.GetRandom(50000, 65000));
} elseif (key == "Research") {
wr.SetCellValue(expanseCol, this.GetRandom(150000, 165000));
} elseif (key == "Travel") {
wr.SetCellValue(expanseCol, this.GetRandom(20000, 25000));
} elseif (key == "Salary") {
wr.SetCellValue(expanseCol, this.GetRandom(4000000, 450000));
} elseif (key == "Software") {
wr.SetCellValue(expanseCol, this.GetRandom(100000, 150000));
}
}
expanseCol++;
}
var incomeSheet = wb.Worksheets.Add("Income");
var incomeHeader = incomeSheet.Rows[0];
var incomeNames = newstring[] { "Year", "Phones", "Computers", "Software", "Services", "Royalties" };
var incomeCol = 0;
foreach (var key in incomeNames) {
incomeSheet.Columns[incomeCol].Width = 5000;
incomeHeader.SetCellValue(incomeCol, key);
for (var i = 1; i < 20; i++) {
var wr = incomeSheet.Rows[i];
if (key == "Year") {
wr.SetCellValue(incomeCol, 2010 + i);
} elseif (key == "Software") {
wr.SetCellValue(incomeCol, this.GetRandom(700000, 850000));
} elseif (key == "Computers") {
wr.SetCellValue(incomeCol, this.GetRandom(250000, 265000));
} elseif (key == "Royalties") {
wr.SetCellValue(incomeCol, this.GetRandom(400000, 450000));
} elseif (key == "Phones") {
wr.SetCellValue(incomeCol, this.GetRandom(6000000, 650000));
} elseif (key == "Services") {
wr.SetCellValue(incomeCol, this.GetRandom(700000, 750000));
}
}
incomeCol++;
}
this.WorkbookParse(wb);
}
publicvoidWorkbookParse(Workbook wb)
{
if (wb == null)
{
this.worksheetRegion = null;
this.selectedRegion = null;
}
else
{
var names = new List<string>();
var worksheets = wb.Worksheets;
var wsCount = worksheets.Count;
for (var i = 0; i < wsCount; i++)
{
var tables = worksheets[i].Tables;
var tCount = tables.Count;
for (var j = 0; j < tCount; j++)
{
names.Add(worksheets[i].Name + " - " + tables[j].Name);
}
}
this.worksheetRegion = names;
this.selectedRegion = names.Count > 0 ? names[0] : null;
}
this.wb = wb;
this.canSave = wb != null;
}
publicdoubleGetRandom(double min, double max)
{
return Math.Round(min + (Rand.NextDouble() * (max - min)));
}
publicstringGetItem(string[] array)
{
var index = (int)Math.Round(GetRandom(0, array.Length - 1));
return array[index];
}
privatevoidSaveFile(Workbook workbook, string fileNameWithoutExtension, WorkbookFormat format)
{
var ms = new System.IO.MemoryStream();
workbook.SetCurrentFormat(format);
workbook.Save(ms);
string extension;
switch (workbook.CurrentFormat)
{
default:
case WorkbookFormat.StrictOpenXml:
case WorkbookFormat.Excel2007:
extension = ".xlsx";
break;
case WorkbookFormat.Excel2007MacroEnabled:
extension = ".xlsm";
break;
case WorkbookFormat.Excel2007MacroEnabledTemplate:
extension = ".xltm";
break;
case WorkbookFormat.Excel2007Template:
extension = ".xltx";
break;
case WorkbookFormat.Excel97To2003:
extension = ".xls";
break;
case WorkbookFormat.Excel97To2003Template:
extension = ".xlt";
break;
}
string fileName = fileNameWithoutExtension + extension;
string mime;
switch (workbook.CurrentFormat)
{
default:
case WorkbookFormat.Excel2007:
case WorkbookFormat.Excel2007MacroEnabled:
case WorkbookFormat.Excel2007MacroEnabledTemplate:
case WorkbookFormat.Excel2007Template:
case WorkbookFormat.StrictOpenXml:
mime = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
break;
case WorkbookFormat.Excel97To2003:
case WorkbookFormat.Excel97To2003Template:
mime = "application/vnd.ms-excel";
break;
}
ms.Position = 0;
var bytes = ms.ToArray();
this.SaveFile(bytes, fileName, mime);
}
JSObject module;
bool moduleDownloaded = false;
publicasyncvoidSaveFile(byte[] bytes, string fileName, string mime)
{
if (Runtime is WebAssemblyJSRuntime wasmRuntime)
{
if (!moduleDownloaded)
{
module = await JSHost.ImportAsync("BlazorFastDownload", "../BlazorFastDownloadFile.js");
moduleDownloaded = true;
}
BlazorFastDownload.DownloadFile(fileName, mime, bytes);
}
elseif (Runtime is IJSInProcessRuntime inProc)
inProc.InvokeVoid("BlazorDownloadFile", fileName, mime, bytes);
}
publicvoidDispose()
{
if (moduleDownloaded && module != null)
{
module.Dispose();
}
}
}razor
// these methods are from:// https://www.meziantou.net/generating-and-downloading-a-file-in-a-blazor-webassembly-application.htmfunctionBlazorDownloadFile(filename, contentType, content) {
// Blazor marshall byte[] to a base64 string, so we first need to convert the string (content) to a Uint8Array to create the Filevar data = base64DecToArr(content);
// Create the URLvar file = new File([data], filename, { type: contentType });
var exportUrl = URL.createObjectURL(file);
// Create the <a> element and click on itvar a = document.createElement("a");
document.body.appendChild(a);
a.href = exportUrl;
a.download = filename;
a.target = "_self";
a.click();
// We don't need to keep the url, let's release the memory
URL.revokeObjectURL(exportUrl);
}
// Convert a base64 string to a Uint8Array. This is needed to create a blob object from the base64 string.// The code comes from: https://developer.mozilla.org/fr/docs/Web/API/WindowBase64/D%C3%A9coder_encoder_en_base64functionb64ToUint6(nChr) {
return nChr > 64 && nChr < 91 ? nChr - 65 : nChr > 96 && nChr < 123 ? nChr - 71 : nChr > 47 && nChr < 58 ? nChr + 4 : nChr === 43 ? 62 : nChr === 47 ? 63 : 0;
}
functionbase64DecToArr(sBase64, nBlocksSize) {
var sB64Enc = sBase64.replace(/[^A-Za-z0-9\+\/]/g, ""), nInLen = sB64Enc.length, nOutLen = nBlocksSize ? Math.ceil((nInLen * 3 + 1 >> 2) / nBlocksSize) * nBlocksSize : nInLen * 3 + 1 >> 2, taBytes = newUint8Array(nOutLen);
for (var nMod3, nMod4, nUint24 = 0, nOutIdx = 0, nInIdx = 0; nInIdx < nInLen; nInIdx++) {
nMod4 = nInIdx & 3;
nUint24 |= b64ToUint6(sB64Enc.charCodeAt(nInIdx)) << 18 - 6 * nMod4;
if (nMod4 === 3 || nInLen - nInIdx === 1) {
for (nMod3 = 0; nMod3 < 3 && nOutIdx < nOutLen; nMod3++, nOutIdx++) {
taBytes[nOutIdx] = nUint24 >>> (16 >>> nMod3 & 24) & 255;
}
nUint24 = 0;
}
}
return taBytes;
}
//# sourceMappingURL=BlazorDownloadFile.js.mapjs
/*
CSS styles are loaded from the shared CSS file located at:
https://static.infragistics.com/xplatform/css/samples/
*/css
Like this sample? Get access to our complete Ignite UI for Blazor toolkit and start building your own apps in minutes. Download it for free.
最速のデータ グリッド、高性能なチャート、すぐに使用できる機能のフルセットなどを含む 60 以上の再利用可能なコンポーネント を使用して、最新の Web エクスペリエンスを構築します。