### Install Magicodes.IE Packages Source: https://github.com/dotnetcore/magicodes.ie/blob/master/docs/4.Use in Docker.md Install the necessary Magicodes.IE packages for Excel and PDF export functionality. ```powershell Install-Package Magicodes.IE.Excel Install-Package Magicodes.IE.Pdf ``` -------------------------------- ### Install Magicodes.IE.Csv Package Source: https://github.com/dotnetcore/magicodes.ie/blob/master/docs/7.Csv Import and Export.md Install the Magicodes.IE.Csv NuGet package using the Package Manager Console. ```powershell Install-Package Magicodes.IE.Csv ``` -------------------------------- ### Install Magicodes.IE.AspNetCore Package Source: https://github.com/dotnetcore/magicodes.ie/blob/master/docs/12.Magicodes.IE.AspNetCore之一行代码多格式导出.md Use the NuGet Package Manager Console to install the necessary package for ASP.NET Core integration. ```powershell Install-Package Magicodes.IE.AspNetCore ``` -------------------------------- ### Install Magicodes.IE.Excel Package Source: https://github.com/dotnetcore/magicodes.ie/wiki/9.Excel模板导出之导出教材订购表 Use this command to install the necessary NuGet package for Excel export functionality. ```powershell Install-Package Magicodes.IE.Excel ``` -------------------------------- ### Install Magicodes.IE.Pdf Package Source: https://github.com/dotnetcore/magicodes.ie/blob/master/docs/3.Basic tutorial of export Pdf receipts.md Use this command in the Package Manager Console to install the necessary NuGet package for PDF export functionality. ```powershell Install-Package Magicodes.IE.Pdf ``` -------------------------------- ### Install Magicodes.IE.Excel.AspNetCore Package Source: https://github.com/dotnetcore/magicodes.ie/blob/master/docs/AspNetCore之快速导出Excel.md Use the NuGet Package Manager Console to install the necessary package for Excel export functionality. ```powershell Install-Package Magicodes.IE.Excel.AspNetCore ``` -------------------------------- ### Install libgdiplus for Excel Export Source: https://github.com/dotnetcore/magicodes.ie/wiki/4.在Docker中使用 If not using the recommended base image, these commands install the libgdiplus library required for Excel export functionality in your Docker container. ```dockerfile # 如不使用上述基础镜像,那么需要添加以下命令来安装libgdiplus库,用于Excel导出 RUN apt-get update && apt-get install -y libgdiplus libc6-dev RUN ln -s /usr/lib/libgdiplus.so /usr/lib/gdiplus.dll ``` -------------------------------- ### Install fontconfig and font for PDF Export Source: https://github.com/dotnetcore/magicodes.ie/blob/master/docs/4.Use in Docker.md Install the fontconfig library and copy a font file to support PDF export functionality. ```dockerfile # Install fontconfig library for Pdf export RUN apt-get update && apt-get install -y fontconfig # Copy font file COPY /simsun.ttc /usr/share/fonts/simsun.ttc ``` -------------------------------- ### Recommended Dockerfile for Magicodes.IE Source: https://github.com/dotnetcore/magicodes.ie/blob/master/docs/4.Use in Docker.md This Dockerfile uses a recommended base image that includes pre-installed libraries for Excel and PDF exports, simplifying the setup process. It also sets the working directory, copies application files, and defines entry points. ```dockerfile #It is recommended that you build with this base image for the reasons given below. This image build has the libgdiplus library installed. FROM ccr.ccs.tencentyun.com/magicodes/aspnetcore-runtime:latest AS base WORKDIR /src RUN ls COPY /src/Magicodes.IE.Exporter/simsun.ttc /usr/share/fonts/simsun.ttc WORKDIR /app EXPOSE 80 EXPOSE 443 FROM mcr.microsoft.com/dotnet/core/sdk:latest AS build WORKDIR /src COPY ["Magicodes.IE.Exporter.csproj", "src/Magicodes.IE.Exporter/"] RUN dotnet restore "src/Magicodes.IE.Exporter/Magicodes.IE.Exporter.csproj" COPY . . WORKDIR "src/Magicodes.IE.Exporter" RUN dotnet build "Magicodes.IE.Exporter.csproj" -c Release -o /app/build FROM build AS publish RUN dotnet publish "Magicodes.IE.Exporter.csproj" -c Release -o /app/publish FROM base AS final WORKDIR /app COPY --from= publish /app/publish . ENTRYPOINT ["dotnet", "Magicodes.IE.Exporter.dll"] ``` -------------------------------- ### Install fontconfig and Copy Fonts for PDF Export Source: https://github.com/dotnetcore/magicodes.ie/wiki/4.在Docker中使用 This snippet installs the fontconfig library and copies a font file to the container, which is necessary for PDF export functionality. ```dockerfile # 安装fontconfig库,用于Pdf导出 RUN apt-get update && apt-get install -y fontconfig # 复制字体文件 COPY /simsun.ttc /usr/share/fonts/simsun.ttc ``` -------------------------------- ### PDF Export with Template and Attributes Source: https://github.com/dotnetcore/magicodes.ie/blob/master/RELEASE.md Provides examples of exporting data to PDF using a template and specifying PDF exporter attributes. ```csharp Task ExportListBytesByTemplate(ICollection<T> data, PdfExporterAttribute pdfExporterAttribute,string temple); ``` ```csharp Task ExportBytesByTemplate<T>(T data, PdfExporterAttribute pdfExporterAttribute,string template); ``` -------------------------------- ### Export Student Data to PDF Source: https://github.com/dotnetcore/magicodes.ie/blob/master/docs/4.Use in Docker.md An example of exporting a list of student data to a PDF file using the PdfExporter. The exported file is then returned as an IActionResult. ```csharp public async Task ExporterPdf() { var exporter = new PdfExporter(); var result = await exporter.ExportListByTemplate(Path.Combine("wwwroot", "test.pdf"), new List() { new StudentPdf { Name = "MR.A", Age = 18, Remarks = "我叫MR.A,今年18岁", Birthday=DateTime.Now }, new StudentPdf { Name = "MR.B", Age = 19, Remarks = "我叫MR.B,今年19岁", Birthday=DateTime.Now }, new StudentPdf { Name = "MR.C", Age = 20, Remarks = "我叫MR.C,今年20岁", Birthday=DateTime.Now } }); return File("test.pdf", "application/pdf", result.FileName); } ``` -------------------------------- ### CSV Export and Import Operations Source: https://context7.com/dotnetcore/magicodes.ie/llms.txt Demonstrates basic CSV export to a file and byte array, and import from a file and stream. Ensure CsvHelper is installed for internal use. ```csharp using Magicodes.ExporterAndImporter.Core; using Magicodes.ExporterAndImporter.Csv; // Export IExporter csvExporter = new CsvExporter(); var data = GenFu.GenFu.ListOf(1000); ExportFileInfo fileInfo = await csvExporter.Export("sales.csv", data); byte[] csvBytes = await csvExporter.ExportAsByteArray(data); // Import IImporter csvImporter = new CsvImporter(); ImportResult result = await csvImporter.Import("sales.csv"); if (!result.HasError) Console.WriteLine($"Imported {result.Data.Count} records from CSV."); else foreach (var err in result.RowErrors) Console.WriteLine($"Row {err.RowIndex}: {string.Join(", ", err.FieldErrors.Values)}"); // Import from stream using var stream = File.OpenRead("sales.csv"); var streamResult = await csvImporter.Import(stream); ``` -------------------------------- ### Export Excel using XlsxFileResult with Byte Array Source: https://github.com/dotnetcore/magicodes.ie/blob/master/docs/AspNetCore之快速导出Excel.md This example demonstrates exporting an Excel file generated from a byte array using XlsxFileResult. Ensure the Magicodes.IE.Excel.AspNetCore package is installed and the namespace is imported. ```csharp using Magicodes.ExporterAndImporter.Excel.AspNetCore; using Magicodes.ExporterAndImporter.Excel; using Microsoft.AspNetCore.Mvc; using System.Threading.Tasks; namespace YourNamespace { [ApiController] [Route("api/[controller]")] public class XlsxFileResultTests : ControllerBase { /// /// 使用Byte数组导出Excel文件 /// /// [HttpGet("ByBytes")] public async Task ByBytes() { //随机生成100条数据 var list = GenFu.GenFu.ListOf(100); var exporter = new ExcelExporter(); var bytes = await exporter.ExportAsByteArray(list); //使用XlsxFileResult进行导出 return new XlsxFileResult(bytes: bytes); } } } ``` -------------------------------- ### Import Images from Excel to Base64 or File Path Source: https://context7.com/dotnetcore/magicodes.ie/llms.txt Use `ImportImageFieldAttribute` to specify how images from Excel should be imported. Set `ImportImageTo.Base64` to get the image as a Base64 string, or provide a directory path to save the image and get its file path. ```csharp using Magicodes.ExporterAndImporter.Core; using Magicodes.ExporterAndImporter.Core.Fields; using Magicodes.ExporterAndImporter.Core.Models; using Magicodes.ExporterAndImporter.Excel; // Import: images stored as Base64 strings public class ProductWithImageImportDto { [ImporterHeader(Name = "Product Name")] public string Name { get; set; } // Import image as base64 string [ImporterHeader(Name = "Photo")] [ImportImageField(ImportImageTo = ImportImageTo.Base64)] public string PhotoBase64 { get; set; } // Import image to specific directory, returns file path [ImporterHeader(Name = "Thumbnail")] [ImportImageField("/var/app/uploads/thumbnails")] public string ThumbnailPath { get; set; } } IExcelImporter importer = new ExcelImporter(); var importResult = await importer.Import("products_with_photos.xlsx"); foreach (var product in importResult.Data) { Console.WriteLine($"{product.Name}: photo Base64 length = {product.PhotoBase64?.Length}"); Console.WriteLine($" Thumbnail saved to: {product.ThumbnailPath}"); } ``` -------------------------------- ### Export Student Data to Excel Source: https://github.com/dotnetcore/magicodes.ie/blob/master/docs/4.Use in Docker.md An example of exporting a list of student data to an Excel file using the ExcelExporter. The exported file is then returned as an IActionResult. ```csharp public async Task ExporterExcel() { IExporter exporter = new ExcelExporter(); var result = await exporter.Export(Path.Combine("wwwroot","test.xlsx"), new List() { new StudentExcel { Name = "MR.A", Age = 18, Remarks = "我叫MR.A,今年18岁", Birthday=DateTime.Now }, new StudentExcel { Name = "MR.B", Age = 19, Remarks = "我叫MR.B,今年19岁", Birthday=DateTime.Now }, new StudentExcel { Name = "MR.C", Age = 20, Remarks = "我叫MR.C,今年20岁", Birthday=DateTime.Now } }); return File("test.xlsx", "application/ms-excel", result.FileName); } ``` -------------------------------- ### Configure Export Formats in .NET Core Source: https://github.com/dotnetcore/magicodes.ie/blob/master/docs/12.Exporting multiple formats in NETCore via request headers.md This code snippet demonstrates the initialization of a trade object with specific properties, including status, time, amount in words, and a code. This is part of the setup for exporting data. ```csharp TradeStatus = "已完成", TradeTime = DateTime.Now, UppercaseAmount = "贰万贰仟玖佰叁拾玖圆肆角叁分", Code = "19071800001" }; } ``` -------------------------------- ### Implement IImportHeaderFilter for Custom Import Logic Source: https://github.com/dotnetcore/magicodes.ie/blob/master/docs/Magicodes.IE之导入导出筛选器.md Implement this interface to customize how import headers and their mappings are processed. This example modifies the header name for 'Name' and sets up a value mapping for 'Gender'. ```csharp /// /// 导入列头筛选器测试 /// 1)测试修改列头 /// 2)测试修改值映射 /// public class ImportHeaderFilterTest : IImportHeaderFilter { public List Filter(List importerHeaderInfos) { foreach (var item in importerHeaderInfos) { if (item.PropertyName == "Name") { item.Header.Name = "Student"; } else if (item.PropertyName == "Gender") { item.MappingValues = new Dictionary() { {"男",0 }, {"女",1 } }; } } return importerHeaderInfos; } } ``` -------------------------------- ### Dynamic Excel Export with JObject Source: https://github.com/dotnetcore/magicodes.ie/blob/master/docs/Excel template export - dynamic export.md This C# code demonstrates how to export data dynamically to an Excel template using a JObject. Ensure you have Newtonsoft.Json installed if you are using JObject. ```csharp string json = @"{ 'Company': '雪雁', 'Address': '湖南长沙', 'Contact': '雪雁', 'Tel': '136xxx', 'BookInfos': [ {'No':'a1','RowNo':1,'Name':'Docker+Kubernetes应用开发与快速上云','EditorInChief':'李文强','PublishingHouse':'机械工业出版社','Price':65,'PurchaseQuantity':10000,'Cover':'https://img9.doubanio.com/view/ark_article_cover/retina/public/135025435.jpg?v=1585121965','Remark':'备注'}, {'No':'a1','RowNo':1,'Name':'Docker+Kubernetes应用开发与快速上云','EditorInChief':'李文强','PublishingHouse':'机械工业出版社','Price':65,'PurchaseQuantity':10000,'Cover':'https://img9.doubanio.com/view/ark_article_cover/retina/public/135025435.jpg?v=1585121965','Remark':'备注'} ] }"; var jobj = JObject.Parse(json); //Template Path var tplPath = Path.Combine(Directory.GetCurrentDirectory(), "TestFiles", "ExportTemplates", "DynamicExportTpl.xlsx"); //Creating Excel Export Objects IExportFileByTemplate exporter = new ExcelExporter(); //Export Path var filePath = Path.Combine(Directory.GetCurrentDirectory(), nameof(DynamicExportByTemplate_Test) + ".xlsx"); if (File.Exists(filePath)) File.Delete(filePath); //Export from template await exporter.ExportByTemplate(filePath, jobj, tplPath); ``` -------------------------------- ### Export Excel using XlsxFileResult with Generic Collection Source: https://github.com/dotnetcore/magicodes.ie/blob/master/docs/AspNetCore之快速导出Excel.md This example demonstrates exporting an Excel file directly from a generic collection using XlsxFileResult. This is a concise way to export data when you have it readily available as a list. ```csharp using Magicodes.ExporterAndImporter.Excel.AspNetCore; using Microsoft.AspNetCore.Mvc; using System.Threading.Tasks; namespace YourNamespace { [ApiController] [Route("api/[controller]")] public class XlsxFileResultTests : ControllerBase { /// /// 使用泛型集合导出Excel文件 /// /// [HttpGet("ByList")] public async Task ByList() { var list = GenFu.GenFu.ListOf(100); return new XlsxFileResult(data: list); } } } ``` -------------------------------- ### Dockerfile with Pre-installed Dependencies Source: https://github.com/dotnetcore/magicodes.ie/wiki/4.在Docker中使用 This Dockerfile uses a recommended base image that includes pre-installed libraries like libgdiplus for Excel exports and is configured for optimal build speed and timezone settings. ```dockerfile #推荐大家使用此基础镜像构建,理由见下文。该镜像通过海外构建已安装libgdiplus库。 FROM ccr.ccs.tencentyun.com/magicodes/aspnetcore-runtime:latest AS base WORKDIR /src RUN ls COPY /src/Magicodes.IE.Exporter/simsun.ttc /usr/share/fonts/simsun.ttc WORKDIR /app EXPOSE 80 EXPOSE 443 FROM mcr.microsoft.com/dotnet/core/sdk:latest AS build WORKDIR /src COPY ["Magicodes.IE.Exporter.csproj", "src/Magicodes.IE.Exporter/"] RUN dotnet restore "src/Magicodes.IE.Exporter/Magicodes.IE.Exporter.csproj" COPY . . WORKDIR "src/Magicodes.IE.Exporter" RUN dotnet build "Magicodes.IE.Exporter.csproj" -c Release -o /app/build FROM build AS publish RUN dotnet publish "Magicodes.IE.Exporter.csproj" -c Release -o /app/publish FROM base AS final WORKDIR /app COPY --from= publish /app/publish . ENTRYPOINT ["dotnet", "Magicodes.IE.Exporter.dll"] ``` -------------------------------- ### Benchmark Configuration Source: https://github.com/dotnetcore/magicodes.ie/blob/master/docs/13.Performance Measurement.md Configuration details for the BenchmarkDotNet tests, including OS, CPU, .NET SDK versions, and runtime environments. ```ini BenchmarkDotNet=v0.12.1, OS=Windows 10.0.18363.836 (1909/November2018Update/19H2) AMD Ryzen 5 3600X, 1 CPU, 12 logical and 6 physical cores .NET Core SDK=5.0.100-preview.4.20258.7 [Host] : .NET Core 3.1.4 (CoreCLR 4.700.20.20201, CoreFX 4.700.20.22101), X64 RyuJIT Job-OONFAJ : .NET Framework 4.8 (4.8.4180.0), X64 RyuJIT Job-YIUEXF : .NET Core 2.2.8 (CoreCLR 4.6.28207.03, CoreFX 4.6.28208.02), X64 RyuJIT Job-LZHMKS : .NET Core 3.1.4 (CoreCLR 4.700.20.20201, CoreFX 4.700.20.22101), X64 RyuJIT IterationCount=5 LaunchCount=1 WarmupCount=1 ``` -------------------------------- ### Basic Excel Export in C# Source: https://github.com/dotnetcore/magicodes.ie/blob/master/docs/2.Basic tutorial of export Excel.md Demonstrates a simple Excel export of a list of Student objects. Ensure the Student class is defined with properties to be exported. ```csharp public class Student { /// /// 姓名 /// public string Name { get; set; } /// /// 年龄 /// public int Age { get; set; } } public async Task Export() { IExporter exporter = new ExcelExporter(); var result = await exporter.Export("a.xlsx", new List() { new Student { Name = "MR.A", Age = 18 }, new Student { Name = "MR.B", Age = 19 }, new Student { Name = "MR.B", Age = 20 } }); } ``` -------------------------------- ### ImportImageTo枚举 Source: https://github.com/dotnetcore/magicodes.ie/wiki/8.Excel图片导入导出 定义图片导入的两种方式:导入到临时目录(TempFolder)或导入为Base64格式(Base64)。 ```csharp /// /// 图片导入类型 /// public enum ImportImageTo { /// /// 导入到临时目录 /// TempFolder, /// /// 导入为base64格式 /// Base64 } ``` -------------------------------- ### Implement IExporterHeaderFilter to Modify Export Headers Source: https://github.com/dotnetcore/magicodes.ie/blob/master/docs/Magicodes.IE之导入导出筛选器.md Implement this interface to customize export headers. This example changes the display name of a column from '名称' to 'name'. ```csharp public class TestExporterHeaderFilter1 : IExporterHeaderFilter { /// /// 表头筛选器(修改名称) /// /// /// public ExporterHeaderInfo Filter(ExporterHeaderInfo exporterHeaderInfo) { if (exporterHeaderInfo.DisplayName.Equals("名称")) { exporterHeaderInfo.DisplayName = "name"; } return exporterHeaderInfo; } } ``` -------------------------------- ### Register Magicodes.IE Middleware Source: https://github.com/dotnetcore/magicodes.ie/blob/master/docs/12.Magicodes.IE.AspNetCore之一行代码多格式导出.md Register the Magicodes.IE middleware in your Startup.cs Configure method after UseRouting() to enable export services. ```csharp public void Configure(IApplicationBuilder app) { app.UseRouting(); app.UseMagiCodesIE(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); } ``` -------------------------------- ### Export Excel using XlsxFileResult with Stream Source: https://github.com/dotnetcore/magicodes.ie/blob/master/docs/AspNetCore之快速导出Excel.md This example shows how to export an Excel file from a MemoryStream using XlsxFileResult. You can specify a custom download file name. ```csharp using Magicodes.ExporterAndImporter.Excel.AspNetCore; using Magicodes.ExporterAndImporter.Excel; using Microsoft.AspNetCore.Mvc; using System.IO; using System.Threading.Tasks; namespace YourNamespace { [ApiController] [Route("api/[controller]")] public class XlsxFileResultTests : ControllerBase { /// /// 使用流导出Excel文件 /// /// [HttpGet("ByStream")] public async Task ByStream() { //随机生成100条数据 var list = GenFu.GenFu.ListOf(100); var exporter = new ExcelExporter(); var result = await exporter.ExportAsByteArray(list); var fs = new MemoryStream(result); return new XlsxFileResult(stream: fs, fileDownloadName: "下载文件"); } } } ``` -------------------------------- ### Unit Test for Excel Template Export Source: https://github.com/dotnetcore/magicodes.ie/wiki/9.Excel模板导出之导出教材订购表 Demonstrates exporting a textbook order detail sheet using a specified Excel template. Ensure the template file exists at the provided path. ```csharp [Fact(DisplayName = "Excel模板导出教材订购明细样表")] public async Task ExportByTemplate_Test() { //模板路径 var tplPath = Path.Combine(Directory.GetCurrentDirectory(), "TestFiles", "ExportTemplates", "2020年春季教材订购明细样表.xlsx"); //创建Excel导出对象 IExportFileByTemplate exporter = new ExcelExporter(); //导出路径 var filePath = Path.Combine(Directory.GetCurrentDirectory(), nameof(ExportByTemplate_Test) + ".xlsx"); if (File.Exists(filePath)) File.Delete(filePath); //根据模板导出 await exporter.ExportByTemplate(filePath, new TextbookOrderInfo("湖南心莱信息科技有限公司", "湖南长沙岳麓区", "雪雁", "1367197xxxx", "雪雁", DateTime.Now.ToLongDateString(), new List() { new BookInfo(1, "0000000001", "《XX从入门到放弃》", "张三", "机械工业出版社", "3.14", 100, "备注"), new BookInfo(2, "0000000002", "《XX从入门到放弃》", "张三", "机械工业出版社", "3.14", 100, "备注"), new BookInfo(3, "0000000003", "《XX从入门到放弃》", "张三", "机械工业出版社", "3.14", 100, "备注") }), tplPath); } ``` -------------------------------- ### Dynamic Export using JObject Source: https://github.com/dotnetcore/magicodes.ie/blob/master/docs/Excel模板导出之动态导出.md Export Excel data dynamically using a JObject. Ensure the Newtonsoft.Json package is installed. This method is suitable for JSON-formatted dynamic data. ```csharp string json = @"{ 'Company': '雪雁', 'Address': '湖南长沙', 'Contact': '雪雁', 'Tel': '136xxx', 'BookInfos': [ {'No':'a1','RowNo':1,'Name':'Docker+Kubernetes应用开发与快速上云','EditorInChief':'李文强','PublishingHouse':'机械工业出版社','Price':65,'PurchaseQuantity':10000,'Cover':'https://img9.doubanio.com/view/ark_article_cover/retina/public/135025435.jpg?v=1585121965','Remark':'备注'}, {'No':'a1','RowNo':1,'Name':'Docker+Kubernetes应用开发与快速上云','EditorInChief':'李文强','PublishingHouse':'机械工业出版社','Price':65,'PurchaseQuantity':10000,'Cover':'https://img9.doubanio.com/view/ark_article_cover/retina/public/135025435.jpg?v=1585121965','Remark':'备注'} ] }"; var jobj = JObject.Parse(json); //模板路径 var tplPath = Path.Combine(Directory.GetCurrentDirectory(), "TestFiles", "ExportTemplates", "DynamicExportTpl.xlsx"); //创建Excel导出对象 IExportFileByTemplate exporter = new ExcelExporter(); //导出路径 var filePath = Path.Combine(Directory.GetCurrentDirectory(), nameof(DynamicExportByTemplate_Test) + ".xlsx"); if (File.Exists(filePath)) File.Delete(filePath); //根据模板导出 await exporter.ExportByTemplate(filePath, jobj, tplPath); ``` -------------------------------- ### Append and Export Data Source: https://github.com/dotnetcore/magicodes.ie/blob/master/README.md Demonstrates how to append multiple data lists and export them to a file, allowing for combined data in a single export operation. ```csharp exporter.Append(list1).SeparateByColumn().Append(list2).ExportAppendData(filePath); ``` -------------------------------- ### Define Student DTO Class Source: https://github.com/dotnetcore/magicodes.ie/blob/master/docs/3.Basic tutorial of export Pdf receipts.md Create a Data Transfer Object (DTO) class to represent the data that will be exported to a PDF. This example defines properties for Name and Age. ```csharp public class Student { /// /// 姓名 /// public string Name { get; set; } /// /// 年龄 /// public int Age { get; set; } } ``` -------------------------------- ### 执行Excel图片导入 Source: https://github.com/dotnetcore/magicodes.ie/wiki/8.Excel图片导入导出 使用Importer.Import方法执行图片导入操作。导入的图片将根据DTO配置保存到临时目录或以Base64格式处理。 ```csharp public async Task ImportPicture_Test() { var filePath = Path.Combine(Directory.GetCurrentDirectory(), "TestFiles", "Import", "图片导入模板.xlsx"); var import = await Importer.Import(filePath); if (import.Exception != null) _testOutputHelper.WriteLine(import.Exception.ToString()); if (import.RowErrors.Count > 0) _testOutputHelper.WriteLine(JsonConvert.SerializeObject(import.RowErrors)); } ``` -------------------------------- ### Implement IExporterHeaderFilter to Modify Column Ignore Property Source: https://github.com/dotnetcore/magicodes.ie/blob/master/docs/Magicodes.IE之导入导出筛选器.md Implement this interface to dynamically change column properties during export. This example sets 'IsIgnore' to false for columns marked as ignored. ```csharp public class TestExporterHeaderFilter2 : IExporterHeaderFilter { /// /// 表头筛选器(修改忽略列) /// /// /// public ExporterHeaderInfo Filter(ExporterHeaderInfo exporterHeaderInfo) { if (exporterHeaderInfo.ExporterHeaderAttribute.IsIgnore) { exporterHeaderInfo.ExporterHeaderAttribute.IsIgnore = false; } return exporterHeaderInfo; } } ``` -------------------------------- ### Register Filters with Dependency Injection in Startup Source: https://github.com/dotnetcore/magicodes.ie/blob/master/docs/Magicodes.IE之导入导出筛选器.md Configure dependency injection in your ASP.NET Core application's startup class to register filter implementations. Injected filters take precedence over attribute-specified filters and are executed globally. ```csharp public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { AppDependencyResolver.Init(app.ApplicationServices); //添加注入关系 services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); } ``` -------------------------------- ### Importing Data with IImportResultFilter Source: https://github.com/dotnetcore/magicodes.ie/blob/master/docs/Magicodes.IE之导入导出筛选器.md Demonstrates how to import data using the Importer class, specifying the source and labeling file paths. The ImportResultFilter will be applied during the import process. ```csharp public async Task ImportResultFilter_Test() { var filePath = Path.Combine(Directory.GetCurrentDirectory(), "TestFiles", "Errors", "数据错误.xlsx"); var labelingFilePath = Path.Combine(Directory.GetCurrentDirectory(), $"{nameof(ImportResultFilter_Test)}.xlsx"); var result = await Importer.Import(filePath, labelingFilePath); } ``` -------------------------------- ### Implement Per-Column Export Header Filter Source: https://context7.com/dotnetcore/magicodes.ie/llms.txt Implement IExporterHeaderFilter to rename, hide, or reorder columns at runtime. Register the filter via attribute or dependency injection. This example demonstrates renaming columns and hiding 'InternalNotes'. ```csharp using Magicodes.ExporterAndImporter.Core; using Magicodes.ExporterAndImporter.Core.Filters; using Magicodes.ExporterAndImporter.Core.Models; using Magicodes.ExporterAndImporter.Excel; // Per-column filter public class LocalizedHeaderFilter : IExporterHeaderFilter { private readonly Dictionary _translations = new() { { "OrderNo", "Numéro de commande" }, { "CustomerName", "Nom du client" }, { "Amount", "Montant" } }; public ExporterHeaderInfo Filter(ExporterHeaderInfo exporterHeaderInfo) { if (_translations.TryGetValue(exporterHeaderInfo.PropertyName, out var translated)) exporterHeaderInfo.DisplayName = translated; // Dynamically hide columns based on runtime context if (exporterHeaderInfo.PropertyName == "InternalNotes") exporterHeaderInfo.IsIgnore = true; return exporterHeaderInfo; } } // Associate filter with the DTO [ExcelExporter(Name = "Commandes", ExporterHeaderFilter = typeof(LocalizedHeaderFilter))] public class OrderExportDto { [ExporterHeader(DisplayName = "OrderNo")] public string OrderNo { get; set; } [ExporterHeader(DisplayName = "CustomerName")] public string CustomerName { get; set; } [ExporterHeader(DisplayName = "Amount", Format = "#,##0.00")] public decimal Amount { get; set; } [ExporterHeader(DisplayName = "InternalNotes")] public string InternalNotes { get; set; } } // Register via DI for dependency-injected filters (ASP.NET Core) // services.AddTransient(); IExporter exporter = new ExcelExporter(); byte[] bytes = await exporter.ExportAsByteArray(new List { new OrderExportDto { OrderNo = "ORD-001", CustomerName = "Dupont SA", Amount = 2500m } }); // Resulting Excel: columns labelled "Numéro de commande", "Nom du client", "Montant" // "InternalNotes" column is hidden ``` -------------------------------- ### Define DTO for Multi-Sheet Import Source: https://github.com/dotnetcore/magicodes.ie/blob/master/docs/6.Import Multi-Sheet Tutorial.md Define a DTO class where each property represents a sheet and is decorated with the ExcelImporter attribute specifying the SheetName. This setup allows the importer to map data from specific sheets to the correct DTO properties. ```csharp public class ImportClassStudentDto { [ExcelImporter(SheetName = "1班导入数据")] public ImportStudentDto Class1Students { get; set; } [ExcelImporter(SheetName = "2班导入数据")] public ImportStudentDto Class2Students { get; set; } } ``` -------------------------------- ### 实现Excel合并行导入 Source: https://github.com/dotnetcore/magicodes.ie/blob/master/docs/Excel合并行导入.md 使用Importer.Import方法导入指定路径下的Excel文件,该方法支持合并行单元格。 ```csharp var filePath = Path.Combine(Directory.GetCurrentDirectory(), "TestFiles", "Import", "合并行.xlsx"); var import = await Importer.Import(filePath); ``` -------------------------------- ### Configure Services with MagicodesFilter Source: https://github.com/dotnetcore/magicodes.ie/blob/master/docs/12.Magicodes.IE.AspNetCore之一行代码多格式导出.md Alternatively, configure services to use MagicodesFilter as a global filter for controllers to enable export functionality. ```csharp public void ConfigureServices(IServiceCollection services) { services.AddControllers(options=>options.Filters.Add(typeof(MagicodesFilter))); } ``` -------------------------------- ### Implement Dynamic Import Header Remapping Source: https://context7.com/dotnetcore/magicodes.ie/llms.txt Implement IImportHeaderFilter to change header names or value mappings before import processing. This is useful for multi-language import files or files with non-standard column names. This example maps French column names to DTO header names. ```csharp using Magicodes.ExporterAndImporter.Core.Filters; using Magicodes.ExporterAndImporter.Core.Models; public class MultiLanguageImportHeaderFilter : IImportHeaderFilter { // Maps French column names → DTO header names private readonly Dictionary _columnMap = new() { { "Numéro étudiant", "Student ID" }, { "Prénom", "Name" }, { "Sexe", "Gender" } }; public List Filter(List importerHeaderInfos) { foreach (var header in importerHeaderInfos) { if (_columnMap.TryGetValue(header.ExcelHeaderAlias ?? "", out var mappedName)) header.ExcelColumnName = mappedName; } return importerHeaderInfos; } } // Bind filter to specific DTO [ExcelImporter(ImportHeaderFilter = typeof(MultiLanguageImportHeaderFilter))] public class StudentImportDtoFR { [ImporterHeader(Name = "Student ID")] public string StudentCode { get; set; } [ImporterHeader(Name = "Name")] public string Name { get; set; } } // Or register globally via DI and let the library inject it: // services.AddTransient(); IExcelImporter importer = new ExcelImporter(); var result = await importer.Import("students_fr.xlsx"); ``` -------------------------------- ### Student Data Import Test Source: https://github.com/dotnetcore/magicodes.ie/blob/master/docs/1.Basic tutorial of importing student data.md Demonstrates how to import student data from an Excel file and check for import errors and data integrity. Assumes the existence of 'ImportStudentDto' and 'Importer'. ```csharp [Fact(DisplayName = "Student base data import")] public async Task StudentInfoImporter_Test() { var filePath = Path.Combine(Directory.GetCurrentDirectory(), "TestFiles", "Import", "学生基础数据导入.xlsx"); var import = await Importer.Import(filePath); import.ShouldNotBeNull(); if (import.Exception != null) _testOutputHelper.WriteLine(import.Exception.ToString()); if (import.RowErrors.Count > 0) _testOutputHelper.WriteLine(JsonConvert.SerializeObject(import.RowErrors)); import.HasError.ShouldBeFalse(); import.Data.ShouldNotBeNull(); import.Data.Count.ShouldBe(16); } ``` -------------------------------- ### Dynamic Export using ExpandoObject Source: https://github.com/dotnetcore/magicodes.ie/wiki/5.动态导出 Supports dynamic export using ExpandoObject, which allows adding and removing members at runtime. The data is shaped using a fields string, and the export can be performed as a byte array. Headers can be customized using filters. ```csharp public async Task ExportAsByteArraySupportDynamicType_Test() { IExporter exporter = new ExcelExporter(); var source = GenFu.GenFu.ListOf(); string fields = "text,number,name"; var shapedData = source.ShapeData(fields) as ICollection; var result = await exporter.ExportAsByteArray(shapedData); File.WriteAllBytes(filePath, result); } ```