### Run MiniExcel Benchmarks Source: https://github.com/mini-software/miniexcel/blob/master/src/README.md Command to execute all benchmarks for MiniExcel. Ensure you have the .NET SDK installed and navigate to the benchmarks directory. ```bash dotnet run -project .\benchmarks\MiniExcel.Benchmarks -c Release -f net9.0 -filter * --join ``` -------------------------------- ### Convert CSV to XLSX and vice versa Source: https://github.com/mini-software/miniexcel/blob/master/README.md Provides code examples for converting between CSV and XLSX file formats using MiniExcel. ```APIDOC ## Convert CSV to XLSX or Convert XLSX to CSV ### Description MiniExcel offers utility methods to convert between XLSX and CSV file formats, supporting both file paths and streams. ### Examples #### Convert XLSX to CSV ```csharp MiniExcel.ConvertXlsxToCsv(xlsxPath, csvPath); MiniExcel.ConvertXlsxToCsv(xlsxStream, csvStream); ``` #### Convert CSV to XLSX ```csharp MiniExcel.ConvertCsvToXlsx(csvPath, xlsxPath); MiniExcel.ConvertCsvToXlsx(csvStream, xlsxStream); ``` #### Using Streams ```csharp using (var excelStream = new FileStream(path: filePath, FileMode.Open, FileAccess.Read)) using (var csvStream = new MemoryStream()) { MiniExcel.ConvertXlsxToCsv(excelStream, csvStream); } ``` ``` -------------------------------- ### Grouped Data Fill with Template Source: https://github.com/mini-software/miniexcel/blob/master/README.md Shows how to use the `@group` and `@header` tags within an Excel template to group and display data. This example uses an asynchronous method for saving. ```csharp var value = new Dictionary() { ["employees"] = new[] { new {name="Jack",department="HR"}, new {name="Jack",department="HR"}, new {name="John",department="HR"}, new {name="John",department="IT"}, new {name="Neo",department="IT"}, new {name="Loan",department="IT"} } }; await MiniExcel.SaveAsByTemplateAsync(path, templatePath, value); ``` -------------------------------- ### Get Columns from Excel Source: https://github.com/mini-software/miniexcel/blob/master/README.md Retrieve a list of column names (e.g., "A", "B") from an Excel file and get the total column count. ```csharp var columns = MiniExcel.GetColumns(path); // e.g result : ["A","B"...] var cnt = columns.Count; // get column count ``` -------------------------------- ### Query Excel from Specific Cell Source: https://github.com/mini-software/miniexcel/blob/master/README.zh-CN.md Reads data from an Excel file starting from a specified cell. The 'useHeaderRow' parameter indicates if the first row should be treated as headers. ```csharp MiniExcel.Query(path,useHeaderRow:true,startCell:"B3") ``` -------------------------------- ### Get Sheets Dimension Source: https://github.com/mini-software/miniexcel/blob/master/README.zh-CN.md Retrieve the dimensions (number of rows and columns) for all sheets in an Excel file using `MiniExcel.GetSheetsDimensions`. ```csharp var dim = MiniExcel.GetSheetsDimensions(path); ``` -------------------------------- ### Get DataReader for CSV Files Source: https://github.com/mini-software/miniexcel/blob/master/README.md Use `MiniExcel.GetReader` to obtain a `DataReader` for iterating through CSV file content row by row. Requires MiniExcel version 1.23.0 or later. ```csharp using (var reader = MiniExcel.GetReader(path,true)) { while (reader.Read()) { for (int i = 0; i < reader.FieldCount; i++) { var value = reader.GetValue(i); } } } ``` -------------------------------- ### Disable AutoFilter Source: https://github.com/mini-software/miniexcel/blob/master/README.zh-CN.md Starting from version 0.19.0, you can disable the AutoFilter feature by setting OpenXmlConfiguration.AutoFilter to false. ```csharp MiniExcel.SaveAs(path, value, configuration: new OpenXmlConfiguration() { AutoFilter = false }); ``` -------------------------------- ### Save to Stream with Control over Overwriting Source: https://github.com/mini-software/miniexcel/blob/master/README.zh-CN.md When saving to a file path, use this approach to manage the stream yourself for greater control. Alternatively, starting from v1.25.0, you can use the 'overwriteFile' parameter to explicitly control whether an existing file should be overwritten. ```csharp using (var stream = File.Create("Demo.xlsx")) MiniExcel.SaveAs(stream,value); ``` ```csharp MiniExcel.SaveAs(path, value, overwriteFile: true); ``` -------------------------------- ### Write Null Values (Enabled) Source: https://github.com/mini-software/miniexcel/blob/master/README.md Configures MiniExcel to write empty cells for null values when saving data. This setting is controlled by `OpenXmlConfiguration.EnableWriteNullValueCell`. The example demonstrates enabling this feature. ```csharp DataTable dt = new DataTable(); /* ... */ DataRow dr = dt.NewRow(); dr["Name1"] = "Somebody once"; dr["Name2"] = null; dr["Name3"] = "told me."; dt.Rows.Add(dr); OpenXmlConfiguration configuration = new OpenXmlConfiguration() { EnableWriteNullValueCell = true // Default value. }; MiniExcel.SaveAs(@"C:\temp\Book1.xlsx", dt, configuration: configuration); ``` -------------------------------- ### Get Sheet Dimensions Source: https://github.com/mini-software/miniexcel/blob/master/README.md Retrieve the dimensions of sheets within an Excel file using MiniExcel. This is useful for understanding the data range of each sheet. ```csharp var dim = MiniExcel.GetSheetDimensions(path); ``` -------------------------------- ### Query Excel to IDictionary Source: https://github.com/mini-software/miniexcel/blob/master/README.zh-CN.md Iterate through Excel rows as dictionaries. Use Cast> for direct casting. Specify start and end cells for range queries (case-sensitive). ```csharp foreach(IDictionary row in MiniExcel.Query(path)) { //.. } ``` ```csharp var rows = MiniExcel.Query(path).Cast>(); ``` ```csharp var rows = MiniExcel.QueryRange(path, startCell: "A2", endCell: "C3").Cast>(); ``` -------------------------------- ### Save Excel File with Overwrite Option Source: https://github.com/mini-software/miniexcel/blob/master/README.md Starting from version 1.25.0, MiniExcel's SaveAs method supports an `overwriteFile` parameter to control whether an existing file should be replaced. Set to `true` to overwrite. ```csharp MiniExcel.SaveAs(path, value, overwriteFile: true); ``` -------------------------------- ### Retrieve Excel Metadata Source: https://context7.com/mini-software/miniexcel/llms.txt Get information about Excel files without loading all data, including sheet names, detailed sheet information (index, name, state), column names, and sheet dimensions (row/column counts). ```csharp using MiniExcelLibs; // Get all sheet names var sheetNames = MiniExcel.GetSheetNames("path/to/file.xlsx"); foreach (var name in sheetNames) { Console.WriteLine($"Sheet: {name}"); } // Get detailed sheet information (including visibility) var sheetInfos = MiniExcel.GetSheetInformations("path/to/file.xlsx"); foreach (var info in sheetInfos) { Console.WriteLine($"Index: {info.Index}, Name: {info.Name}, State: {info.State}"); } // Get column names var columns = MiniExcel.GetColumns("path/to/file.xlsx", useHeaderRow: true); Console.WriteLine($"Columns: {string.Join(", ", columns)}"); // Get sheet dimensions (row and column counts) var dimensions = MiniExcel.GetSheetDimensions("path/to/file.xlsx"); foreach (var dim in dimensions) { Console.WriteLine($"Sheet: {dim.SheetName}, Rows: {dim.Rows.Count}, Columns: {dim.Columns.Count}"); } // Query all sheets foreach (var sheetName in MiniExcel.GetSheetNames("path/to/file.xlsx")) { var rows = MiniExcel.Query("path/to/file.xlsx", sheetName: sheetName, useHeaderRow: true); Console.WriteLine($"Processing {sheetName}..."); } ``` -------------------------------- ### List GitHub Projects using Template Source: https://github.com/mini-software/miniexcel/blob/master/README.md Demonstrates how to populate an Excel template with a list of GitHub projects and associated data. Requires a template file and a value object containing project details. ```csharp var projects = new[] { new {Name = "MiniExcel",Link="https://github.com/mini-software/MiniExcel",Star=146, CreateTime=new DateTime(2021,03,01)}, new {Name = "HtmlTableHelper",Link="https://github.com/mini-software/HtmlTableHelper",Star=16, CreateTime=new DateTime(2020,02,01)}, new {Name = "PocoClassGenerator",Link="https://github.com/mini-software/PocoClassGenerator",Star=16, CreateTime=new DateTime(2019,03,17)} }; var value = new { User = "ITWeiHan", Projects = projects, TotalStar = projects.Sum(s => s.Star) }; MiniExcel.SaveAsByTemplate(path, templatePath, value); ``` -------------------------------- ### Save Excel File Using Stream Source: https://github.com/mini-software/miniexcel/blob/master/README.md Demonstrates how to save data to an Excel file using a stream, which can be useful for custom file creation logic. Ensure to properly dispose of the stream. ```csharp using (var stream = File.Create("Demo.xlsx")) MiniExcel.SaveAs(stream,value); ``` -------------------------------- ### Custom Buffer Size Source: https://github.com/mini-software/miniexcel/blob/master/README.md Illustrates how to configure the buffer size for file operations. ```APIDOC ## Custom Buffer Size ### Description You can customize the buffer size used during file operations by implementing the `Configuration` interface. ### Example ```csharp public abstract class Configuration : IConfiguration { public int BufferSize { get; set; } = 1024 * 512; // Default buffer size } ``` ``` -------------------------------- ### Custom Buffer Size Configuration Source: https://github.com/mini-software/miniexcel/blob/master/README.md Configure the buffer size for operations by implementing the `IConfiguration` interface and setting the `BufferSize` property. The default is 512KB. ```csharp public abstract class Configuration : IConfiguration { public int BufferSize { get; set; } = 1024 * 512; } ``` -------------------------------- ### Configure Columns Dynamically at Runtime Source: https://context7.com/mini-software/miniexcel/llms.txt Dynamically configure column properties like ignore, index, width, name, and custom formatting at runtime using OpenXmlConfiguration. Useful when attributes are not feasible. ```csharp using MiniExcelLibs; using MiniExcelLibs.OpenXml; using MiniExcelLib.Core.Attributes; // Note: This using directive might be incorrect based on typical MiniExcel usage. var config = new OpenXmlConfiguration { DynamicColumns = new DynamicExcelColumn[] { new("id") { Ignore = true }, // Hide column new("name") { Index = 1, Width = 20, Name = "Full Name" }, // Customize new("createdate") { Index = 0, Format = "yyyy-MM-dd", Width = 15 }, new("point") { Index = 2, Name = "Account Points" }, new("salary") { CustomFormatter = val => val is decimal d ? "$" + d.ToString("N2") : val // Custom format } } }; var data = new[] { new { id = 1, name = "Jack", createdate = new DateTime(2022, 04, 12), point = 123.456, salary = 50000m } }; MiniExcel.SaveAs("output.xlsx", data, configuration: config); ``` -------------------------------- ### Paginate Excel Data with MiniExcel Source: https://github.com/mini-software/miniexcel/blob/master/README.zh-CN.md This C# code demonstrates how to query data from an Excel file and paginate the results using the Skip and Take methods. It's useful for handling large datasets efficiently. ```csharp void Main() { var rows = MiniExcel.Query(path); Console.WriteLine("==== No.1 Page ===="); Console.WriteLine(Page(rows,pageSize:3,page:1)); Console.WriteLine("==== No.50 Page ===="); Console.WriteLine(Page(rows,pageSize:3,page:50)); Console.WriteLine("==== No.5000 Page ===="); Console.WriteLine(Page(rows,pageSize:3,page:5000)); } public static IEnumerable Page(IEnumerable en, int pageSize, int page) { return en.Skip(page * pageSize).Take(pageSize); } ``` -------------------------------- ### Configure OpenXml Excel Generation Options Source: https://context7.com/mini-software/miniexcel/llms.txt Set advanced options for Excel generation, such as table styles, auto-filter, freeze panes, column width, content handling, template parameters, and performance settings. Use this for fine-tuning Excel output. ```csharp using MiniExcelLibs; using MiniExcelLibs.OpenXml; var config = new OpenXmlConfiguration { // Styling TableStyles = TableStyles.Default, // or TableStyles.None AutoFilter = true, // Enable header auto-filter FreezeRowCount = 1, // Rows to freeze (default: 1) FreezeColumnCount = 0, // Columns to freeze (default: 0) EnableAutoWidth = true, // Auto-calculate column widths MinWidth = 8.42857143, // Minimum column width MaxWidth = 200, // Maximum column width // Content handling FillMergedCells = true, // Fill merged cell values when reading EnableConvertByteArray = true, // Convert byte[] to images EnableWriteNullValueCell = true, // Write cells for null values WriteEmptyStringAsNull = false, // Treat empty strings as null TrimColumnNames = true, // Trim whitespace from column names IgnoreEmptyRows = false, // Skip empty rows when reading // Template options IgnoreTemplateParameterMissing = true, // Don't throw on missing template params // Performance - disk cache for large shared strings EnableSharedStringCache = true, // Use disk cache for large files SharedStringCacheSize = 5 * 1024 * 1024, // Cache threshold (5MB) SharedStringCachePath = Path.GetTempPath(), // Cache directory // Performance mode (uses more memory but faster) FastMode = false, BufferSize = 1024 * 512, // Buffer size in bytes // Culture for formatting Culture = CultureInfo.InvariantCulture }; MiniExcel.SaveAs("configured.xlsx", data, configuration: config); ``` -------------------------------- ### Enable Fast Mode for Faster Saving Source: https://github.com/mini-software/miniexcel/blob/master/README.md Set `FastMode` to `true` in `OpenXmlConfiguration` to potentially increase save speed at the cost of memory control. ```csharp var config = new OpenXmlConfiguration() { FastMode = true }; MiniExcel.SaveAs(path, reader,configuration:config); ``` -------------------------------- ### FastMode for Saving Source: https://github.com/mini-software/miniexcel/blob/master/README.md Explains the `FastMode` option for potentially faster saving operations at the cost of memory management. ```APIDOC ## FastMode ### Description Enabling `FastMode` can lead to faster save speeds. However, the system will not actively manage memory, which might be suitable for scenarios where memory usage is not a primary concern. ### Usage ```csharp var config = new OpenXmlConfiguration() { FastMode = true }; MiniExcel.SaveAs(path, reader, configuration: config); ``` ``` -------------------------------- ### Fill Excel Templates Source: https://context7.com/mini-software/miniexcel/llms.txt Generate Excel files by filling data into a template file that uses Vue-like syntax for placeholders (e.g., {{variable}} or {{collection.field}}). Supports POCOs, Dictionaries, and byte arrays for templates. Asynchronous filling is also available. ```csharp using MiniExcelLibs; // Template uses {{variable}} syntax for single values // and {{collection.field}} for collections // Fill template with POCO var value = new { Title = "Sales Report", Date = DateTime.Now, Employees = new[] { new { Name = "Jack", Department = "HR", Salary = 50000 }, new { Name = "Lisa", Department = "HR", Salary = 55000 }, new { Name = "John", Department = "IT", Salary = 65000 } } }; MiniExcel.SaveAsByTemplate("output.xlsx", "template.xlsx", value); // Fill template with Dictionary var dictValue = new Dictionary { ["Title"] = "FooCompany", ["managers"] = new[] { new { name = "Jack", department = "HR" }, new { name = "Loan", department = "IT" } }, ["employees"] = new[] { new { name = "Wade", department = "HR" }, new { name = "Felix", department = "HR" }, new { name = "Eric", department = "IT" } } }; MiniExcel.SaveAsByTemplate("report.xlsx", "template.xlsx", dictValue); // Fill template from byte array (useful for caching templates) byte[] templateBytes = File.ReadAllBytes("template.xlsx"); MiniExcel.SaveAsByTemplate("output.xlsx", templateBytes, value); // Async template filling await MiniExcel.SaveAsByTemplateAsync("output.xlsx", "template.xlsx", value); ``` -------------------------------- ### Dynamic i18n and Permissions Management with IEnumerable Source: https://github.com/mini-software/miniexcel/blob/master/README.zh-CN.md Process i18n and permissions dynamically with low memory usage by using `yield return` to return `IEnumerable>`. This approach is suitable for handling large datasets. ```csharp void Main() { var value = new Order[] { new Order(){OrderNo = "SO01",CustomerID="C001",ProductID="P001",Qty=100,Amt=500}, new Order(){OrderNo = "SO02",CustomerID="C002",ProductID="P002",Qty=300,Amt=400}, }; Console.WriteLine("en-Us and Sales role"); { var path = Path.GetTempPath() + Guid.NewGuid() + ".xlsx"; var lang = "en-US"; var role = "Sales"; MiniExcel.SaveAs(path, GetOrders(lang, role, value)); MiniExcel.Query(path, true).Dump(); } Console.WriteLine("zh-CN and PMC role"); { var path = Path.GetTempPath() + Guid.NewGuid() + ".xlsx"; var lang = "zh-CN"; var role = "PMC"; MiniExcel.SaveAs(path, GetOrders(lang, role, value)); MiniExcel.Query(path, true).Dump(); } } private IEnumerable> GetOrders(string lang, string role, Order[] orders) { foreach (var order in orders) { var newOrder = new Dictionary(); if (lang == "zh-CN") { newOrder.Add("客户编号", order.CustomerID); newOrder.Add("订单编号", order.OrderNo); newOrder.Add("产品编号", order.ProductID); newOrder.Add("数量", order.Qty); if (role == "Sales") newOrder.Add("价格", order.Amt); yield return newOrder; } else if (lang == "en-US") { newOrder.Add("Customer ID", order.CustomerID); newOrder.Add("Order No", order.OrderNo); newOrder.Add("Product ID", order.ProductID); newOrder.Add("Quantity", order.Qty); if (role == "Sales") newOrder.Add("Amount", order.Amt); yield return newOrder; } else { throw new InvalidDataException($"lang {lang} wrong"); } } } public class Order { public string OrderNo { get; set; } public string CustomerID { get; set; } public decimal Qty { get; set; } public string ProductID { get; set; } public decimal Amt { get; set; } } ``` -------------------------------- ### Export Byte Array as File Source: https://github.com/mini-software/miniexcel/blob/master/README.zh-CN.md From version 1.22.0, byte arrays are automatically converted to file paths for import. Disable this with OpenXmlConfiguration.EnableConvertByteArray to false for efficiency if not needed. -------------------------------- ### Configure Template Parameter Missing Handling Source: https://github.com/mini-software/miniexcel/blob/master/README.md Explains how to control the behavior when a template parameter is missing. Setting `IgnoreTemplateParameterMissing` to `false` will cause an exception, while `true` (default) replaces missing parameters with an empty string. ```csharp var config = new OpenXmlConfiguration() { IgnoreTemplateParameterMissing = false, }; MiniExcel.SaveAsByTemplate(path, templatePath, value, config); ``` -------------------------------- ### CSV Configuration: Read Empty String as Null Source: https://github.com/mini-software/miniexcel/blob/master/README.md Demonstrates how to configure MiniExcel to read empty strings in CSV files as null values. ```APIDOC ## CSV Configuration: Read Empty String as Null ### Description By default, empty values in CSV files are mapped to `string.Empty`. This configuration allows you to change this behavior to map them to `null`. ### Method ```csharp var config = new MiniExcelLibs.Csv.CsvConfiguration() { ReadEmptyStringAsNull = true }; ``` ``` -------------------------------- ### Create Multiple Worksheets Source: https://github.com/mini-software/miniexcel/blob/master/README.zh-CN.md Generate Excel files with multiple sheets using either a Dictionary of string to object or a DataSet. Ensure data types are compatible. ```csharp // 1. Dictionary var users = new[] { new { Name = "Jack", Age = 25 }, new { Name = "Mike", Age = 44 } }; var department = new[] { new { ID = "01", Name = "HR" }, new { ID = "02", Name = "IT" } }; var sheets = new Dictionary { ["users"] = users, ["department"] = department }; MiniExcel.SaveAs(path, sheets); ``` ```csharp // 2. DataSet var sheets = new DataSet(); sheets.Add(UsersDataTable); sheets.Add(DepartmentDataTable); //.. MiniExcel.SaveAs(path, sheets); ``` -------------------------------- ### CSV Support and Configuration Source: https://context7.com/mini-software/miniexcel/llms.txt Work with CSV files using the MiniExcel API, including querying and exporting data. Custom configurations for separators, encodings, and parsing logic are supported. ```csharp using MiniExcelLibs; using MiniExcelLibs.Csv; // Query CSV file var csvRows = MiniExcel.Query("data.csv", useHeaderRow: true).ToList(); ``` ```csharp using MiniExcelLibs; // Export to CSV var data = new[] { new { Name = "Jack", Age = 25 }, new { Name = "Mike", Age = 30 } }; MiniExcel.SaveAs("output.csv", data); ``` ```csharp using MiniExcelLibs; using MiniExcelLibs.Csv; using System.Text.RegularExpressions; using System.Text; // CSV with custom configuration var csvConfig = new CsvConfiguration { Seperator = ';', NewLine = "\n", ReadEmptyStringAsNull = true, AlwaysQuote = true, StreamReaderFunc = stream => new StreamReader(stream, Encoding.GetEncoding("gb2312")), StreamWriterFunc = stream => new StreamWriter(stream, Encoding.GetEncoding("gb2312")), SplitFn = row => Regex.Split(row, @"[\t,](?=(?:[^"]|"[^"]*")*$)") .Select(s => Regex.Replace(s.Replace("""", """), "^\"|\"$", "")) .ToArray() }; MiniExcel.SaveAs("custom.csv", data, configuration: csvConfig); var customCsvRows = MiniExcel.Query("custom.csv", configuration: csvConfig).ToList(); ``` -------------------------------- ### Using DataTable as Template Parameter Source: https://github.com/mini-software/miniexcel/blob/master/README.md Demonstrates how to pass a System.Data.DataTable object as a parameter to populate an Excel template. Ensures the DataTable has the correct columns and rows. ```csharp var managers = new DataTable(); { managers.Columns.Add("name"); managers.Columns.Add("department"); managers.Rows.Add("Jack", "HR"); managers.Rows.Add("Loan", "IT"); } var value = new Dictionary() { ["title"] = "FooCompany", ["managers"] = managers, }; MiniExcel.SaveAsByTemplate(path, templatePath, value); ``` -------------------------------- ### Download Excel from MemoryStream in ASP.NET Core Source: https://github.com/mini-software/miniexcel/blob/master/README.md Create an Excel file in memory and return it as a FileStreamResult for download in an ASP.NET Core application. Ensure the stream is reset to the beginning before returning. ```csharp public IActionResult DownloadExcel() { var values = new[] { new { Column1 = "MiniExcel", Column2 = 1 }, new { Column1 = "Github", Column2 = 2} }; var memoryStream = new MemoryStream(); memoryStream.SaveAs(values); memoryStream.Seek(0, SeekOrigin.Begin); return new FileStreamResult(memoryStream, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet") { FileDownloadName = "demo.xlsx" }; } ``` -------------------------------- ### Dynamic Column Configuration with DynamicColumnAttribute Source: https://github.com/mini-software/miniexcel/blob/master/README.md Configure column attributes dynamically using OpenXmlConfiguration and DynamicExcelColumn. This allows setting properties like Ignore, Index, Width, Format, and Name programmatically. ```csharp var config = new OpenXmlConfiguration { DynamicColumns = new DynamicExcelColumn[] { new DynamicExcelColumn("id"){Ignore=true}, new DynamicExcelColumn("name"){Index=1,Width=10}, new DynamicExcelColumn("createdate"){Index=0,Format="yyyy-MM-dd",Width=15}, new DynamicExcelColumn("point"){Index=2,Name="Account Point"}, } }; var path = PathHelper.GetTempPath(); var value = new[] { new { id = 1, name = "Jack", createdate = new DateTime(2022, 04, 12) ,point = 123.456} }; MiniExcel.SaveAs(path, value, configuration: config); ``` -------------------------------- ### Excel Formulas with Template References Source: https://github.com/mini-software/miniexcel/blob/master/README.md Shows how to embed Excel formulas within a template, using special tags like `$enumrowstart` and `$enumrowend` to reference dynamic ranges based on enumerable data. ```excel-formula $=SUM(C{{$enumrowstart}}:C{{$enumrowend}}) ``` ```excel-formula $=SUM(C{{$enumrowstart}}:C{{$enumrowend}}) / COUNT(C{{$enumrowstart}}:C{{$enumrowend}}) ``` ```excel-formula $=MAX(C{{$enumrowstart}}:C{{$enumrowend}}) - MIN(C{{$enumrowstart}}:C{{$enumrowend}}) ``` -------------------------------- ### Configure TableStyles to None Source: https://github.com/mini-software/miniexcel/blob/master/README.md Disable default table styles when exporting to Excel by setting OpenXmlConfiguration.TableStyles to TableStyles.None. ```csharp var config = new OpenXmlConfiguration() { TableStyles = TableStyles.None }; MiniExcel.SaveAs(path, value,configuration:config); ``` -------------------------------- ### Query Excel Data as Dynamic Objects Source: https://context7.com/mini-software/miniexcel/llms.txt Query Excel files row-by-row using dynamic objects. Supports using column headers (A, B, C...), the first row as headers, specific sheet names, and LINQ for efficient paging. Includes an asynchronous query option with IAsyncEnumerable. ```csharp using MiniExcelLibs; // Query with column headers (A, B, C...) var rows = MiniExcel.Query("path/to/file.xlsx").ToList(); Console.WriteLine(rows[0].A); // Access first column Console.WriteLine(rows[0].B); // Access second column // Query using first row as header var rowsWithHeader = MiniExcel.Query("path/to/file.xlsx", useHeaderRow: true).ToList(); Console.WriteLine(rowsWithHeader[0].Name); // Access by column name Console.WriteLine(rowsWithHeader[0].Age); // Query specific sheet var sheetData = MiniExcel.Query("path/to/file.xlsx", sheetName: "Sheet2").ToList(); // Query with LINQ - efficient paging (only reads needed rows) var firstTenRows = MiniExcel.Query("path/to/file.xlsx").Take(10).ToList(); var pageTwo = MiniExcel.Query("path/to/file.xlsx").Skip(10).Take(10).ToList(); // Async query with IAsyncEnumerable await foreach (var row in MiniExcel.QueryAsync("path/to/file.xlsx", useHeaderRow: true)) { Console.WriteLine($"Processing: {row.Name}"); } ``` -------------------------------- ### Query Sheet Visibility State using GetSheetInformations Source: https://github.com/mini-software/miniexcel/blob/master/README.md Obtain information about each sheet in an Excel file, including its index, name, and visibility state (visible/hidden), using the `GetSheetInformations` method. This is useful for understanding the structure and presentation of an Excel workbook. ```csharp var sheets = MiniExcel.GetSheetInformations(path); foreach (var sheetInfo in sheets) { Console.WriteLine($"sheet index : {sheetInfo.Index} "); // next sheet index - numbered from 0 Console.WriteLine($"sheet name : {sheetInfo.Name} "); // sheet name Console.WriteLine($"sheet state : {sheetInfo.State} "); // sheet visibility state - visible / hidden } ``` -------------------------------- ### Convert Between XLSX and CSV Formats Source: https://github.com/mini-software/miniexcel/blob/master/README.md Utilize `MiniExcel.ConvertXlsxToCsv` and `MiniExcel.ConvertCsvToXlsx` for converting between Excel and CSV file formats, supporting both file paths and streams. ```csharp MiniExcel.ConvertXlsxToCsv(xlsxPath, csvPath); MiniExcel.ConvertXlsxToCsv(xlsxStream, csvStream); MiniExcel.ConvertCsvToXlsx(csvPath, xlsxPath); MiniExcel.ConvertCsvToXlsx(csvStream, xlsxStream); ``` ```csharp using (var excelStream = new FileStream(path: filePath, FileMode.Open, FileAccess.Read)) using (var csvStream = new MemoryStream()) { MiniExcel.ConvertXlsxToCsv(excelStream, csvStream); } ``` -------------------------------- ### Query Excel to Dynamic Objects Source: https://github.com/mini-software/miniexcel/blob/master/README.md Execute a query and map it to a list of dynamic objects without using the header row. Dynamic keys are in the format 'A.B.C.D..'. This method is useful when the Excel structure is not known beforehand or when dealing with simple key-value pairs. ```csharp var rows = MiniExcel.Query(path).ToList(); // or using (var stream = File.OpenRead(path)) { var rows = stream.Query().ToList(); Assert.Equal("MiniExcel", rows[0].A); Assert.Equal(1, rows[0].B); Assert.Equal("Github", rows[1].A); Assert.Equal(2, rows[1].B); } ``` -------------------------------- ### Save Excel with Dapper Query (NoCache) Source: https://github.com/mini-software/miniexcel/blob/master/README.md Export results from a Dapper query to an Excel file using CommandFlags.NoCache for efficiency. Avoids potential 'close connection' exceptions with QueryAsync. ```csharp using (var connection = GetConnection(connectionString)) { var rows = connection.Query( new CommandDefinition( "select 'MiniExcel' as Column1,1 as Column2 union all select 'Github',2" , flags: CommandFlags.NoCache) ); // Note: QueryAsync will throw close connection exception MiniExcel.SaveAs(path, rows); } ``` -------------------------------- ### DataReader Usage Source: https://github.com/mini-software/miniexcel/blob/master/README.md Shows how to use the `GetReader` method to read data from an Excel file row by row. ```APIDOC ## DataReader: GetReader ### Description Introduced in version 1.23.0, `GetReader` provides a way to iterate through the data in an Excel file. ### Method ```csharp using (var reader = MiniExcel.GetReader(path, true)) { while (reader.Read()) { for (int i = 0; i < reader.FieldCount; i++) { var value = reader.GetValue(i); } } } ``` ``` -------------------------------- ### Generate Excel Report from Template in ASP.NET Core Source: https://context7.com/mini-software/miniexcel/llms.txt Create an Excel report using a template file in an ASP.NET Core API. Data is passed to the template engine for dynamic content generation. ```csharp using MiniExcelLibs; using Microsoft.AspNetCore.Mvc; [ApiController] [Route("api/[controller]")] public class ExcelController : ControllerBase { // Download from template [HttpGet("report")] public async Task GenerateReport() { var value = new Dictionary { ["title"] = "Monthly Report", ["date"] = DateTime.Now, ["items"] = GetReportItems() }; var stream = new MemoryStream(); await stream.SaveAsByTemplateAsync("Templates/report.xlsx", value); stream.Seek(0, SeekOrigin.Begin); return File(stream, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "report.xlsx"); } } ``` -------------------------------- ### ASP.NET Core Controller for Excel Operations Source: https://github.com/mini-software/miniexcel/blob/master/README.zh-CN.md This controller handles HTTP requests for downloading and uploading Excel files. It includes actions for generating Excel from data, from template files, and from template byte arrays, as well as an action to process uploaded Excel files. ```csharp public class ApiController : Controller { public IActionResult Index() { return new ContentResult { ContentType = "text/html", StatusCode = (int)HttpStatusCode.OK, Content = @" DownloadExcel
DownloadExcelFromTemplatePath
DownloadExcelFromTemplateBytes

Upload Excel


" }; } public IActionResult DownloadExcel() { var values = new[] { new { Column1 = "MiniExcel", Column2 = 1 }, new { Column1 = "Github", Column2 = 2} }; var memoryStream = new MemoryStream(); memoryStream.SaveAs(values); memoryStream.Seek(0, SeekOrigin.Begin); return new FileStreamResult(memoryStream, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet") { FileDownloadName = "demo.xlsx" }; } public IActionResult DownloadExcelFromTemplatePath() { string templatePath = "TestTemplateComplex.xlsx"; Dictionary value = new Dictionary() { ["title"] = "FooCompany", ["managers"] = new[] { new {name="Jack",department="HR"}, new {name="Loan",department="IT"} }, ["employees"] = new[] { new {name="Wade",department="HR"}, new {name="Felix",department="HR"}, new {name="Eric",department="IT"}, new {name="Keaton",department="IT"} } }; MemoryStream memoryStream = new MemoryStream(); memoryStream.SaveAsByTemplate(templatePath, value); memoryStream.Seek(0, SeekOrigin.Begin); return new FileStreamResult(memoryStream, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet") { FileDownloadName = "demo.xlsx" }; } private static Dictionary TemplateBytesCache = new Dictionary(); static ApiController() { string templatePath = "TestTemplateComplex.xlsx"; byte[] bytes = System.IO.File.ReadAllBytes(templatePath); TemplateBytesCache.Add(templatePath, bytes); } public IActionResult DownloadExcelFromTemplateBytes() { byte[] bytes = TemplateBytesCache["TestTemplateComplex.xlsx"]; Dictionary value = new Dictionary() { ["title"] = "FooCompany", ["managers"] = new[] { new {name="Jack",department="HR"}, new {name="Loan",department="IT"} }, ["employees"] = new[] { new {name="Wade",department="HR"}, new {name="Felix",department="HR"}, new {name="Eric",department="IT"}, new {name="Keaton",department="IT"} } }; MemoryStream memoryStream = new MemoryStream(); memoryStream.SaveAsByTemplate(bytes, value); memoryStream.Seek(0, SeekOrigin.Begin); return new FileStreamResult(memoryStream, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet") { FileDownloadName = "demo.xlsx" }; } public IActionResult UploadExcel(IFormFile excel) { var stream = new MemoryStream(); excel.CopyTo(stream); foreach (var item in stream.Query(true)) { // do your logic etc. } return Ok("File uploaded successfully"); } } ``` -------------------------------- ### Download Excel File in ASP.NET Core Source: https://context7.com/mini-software/miniexcel/llms.txt Generate and download an Excel file from an ASP.NET Core API endpoint. Ensure the stream is properly seeked before returning as a File result. ```csharp using MiniExcelLibs; using Microsoft.AspNetCore.Mvc; [ApiController] [Route("api/[controller]")] public class ExcelController : ControllerBase { // Download Excel file [HttpGet("download")] public IActionResult DownloadExcel() { var data = new[] { new { Column1 = "MiniExcel", Column2 = 1 }, new { Column1 = "Github", Column2 = 2 } }; var stream = new MemoryStream(); stream.SaveAs(data); stream.Seek(0, SeekOrigin.Begin); return File(stream, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "export.xlsx"); } ``` -------------------------------- ### Query Data from Multiple Worksheets Source: https://github.com/mini-software/miniexcel/blob/master/README.zh-CN.md Iterate through all sheets in an Excel file, retrieve their names using `MiniExcel.GetSheetNames`, and then query data from each sheet using `MiniExcel.Query` by specifying the `sheetName` parameter. ```csharp var sheets = MiniExcel.GetSheetNames(path); foreach (var sheet in sheets) { Console.WriteLine($"sheet name : {sheet} "); var rows = MiniExcel.Query(path,useHeaderRow:true,sheetName:sheet); Console.WriteLine(rows); } ``` -------------------------------- ### Create Multiple Excel Sheets with Dictionary Source: https://github.com/mini-software/miniexcel/blob/master/README.md Export data to multiple sheets in a single Excel file using a Dictionary where keys are sheet names and values are the data (e.g., arrays of objects). ```csharp // 1. Dictionary var users = new[] { new { Name = "Jack", Age = 25 }, new { Name = "Mike", Age = 44 } }; var department = new[] { new { ID = "01", Name = "HR" }, new { ID = "02", Name = "IT" } }; var sheets = new Dictionary { ["users"] = users, ["department"] = department }; MiniExcel.SaveAs(path, sheets); ``` -------------------------------- ### Query First Row with LINQ Source: https://github.com/mini-software/miniexcel/blob/master/README.md Retrieve the first row of data from an Excel file using the LINQ First() extension method. Assumes the first column is named 'A'. ```csharp var row = MiniExcel.Query(path).First(); Assert.Equal("HelloWorld", row.A); ``` ```csharp using (var stream = File.OpenRead(path)) { var row = stream.Query().First(); Assert.Equal("HelloWorld", row.A); } ``` -------------------------------- ### Simplified Column Configuration with ExcelColumnAttribute Source: https://github.com/mini-software/miniexcel/blob/master/README.md Use the ExcelColumn attribute to consolidate multiple column settings like Name, Index, Format, and Width into a single attribute for cleaner code. ```csharp public class TestIssueI4ZYUUDto { [ExcelColumn(Name = "ID",Index =0)] public string MyProperty { get; set; } [ExcelColumn(Name = "CreateDate", Index = 1,Format ="yyyy-MM",Width =100)] public DateTime MyProperty2 { get; set; } } ``` -------------------------------- ### Create Multiple Excel Sheets with DataSet Source: https://github.com/mini-software/miniexcel/blob/master/README.md Export data to multiple sheets in a single Excel file using a DataSet. Each DataTable in the DataSet will become a sheet. ```csharp // 2. DataSet var sheets = new DataSet(); sheets.Add(UsersDataTable); sheets.Add(DepartmentDataTable); //.. MiniExcel.SaveAs(path, sheets); ``` -------------------------------- ### Fill Template with POCO or Dictionary Source: https://github.com/mini-software/miniexcel/blob/master/README.md Use MiniExcel.SaveAsByTemplate to fill an Excel template with data provided as a POCO object or a Dictionary. Ensure the template path and output path are correctly specified. ```csharp // 1. By POCO var value = new { Name = "Jack", CreateDate = new DateTime(2021, 01, 01), VIP = true, Points = 123 }; MiniExcel.SaveAsByTemplate(path, templatePath, value); // 2. By Dictionary var value = new Dictionary() { ["Name"] = "Jack", ["CreateDate"] = new DateTime(2021, 01, 01), ["VIP"] = true, ["Points"] = 123 }; MiniExcel.SaveAsByTemplate(path, templatePath, value); ``` -------------------------------- ### Export Multiple Sheets to Excel Source: https://context7.com/mini-software/miniexcel/llms.txt Create an Excel workbook containing multiple worksheets from different data sources like arrays or DataSets. Data can be organized using a Dictionary where keys represent sheet names. ```csharp using MiniExcelLibs; var users = new[] { new { Name = "Jack", Age = 25 }, new { Name = "Mike", Age = 44 } }; var departments = new[] { new { ID = "01", Name = "HR" }, new { ID = "02", Name = "IT" } }; // Create multi-sheet workbook using Dictionary var sheets = new Dictionary { ["Users"] = users, ["Departments"] = departments }; MiniExcel.SaveAs("multi-sheet.xlsx", sheets); // Or using DataSet var dataSet = new DataSet(); dataSet.Tables.Add(CreateUsersDataTable()); dataSet.Tables.Add(CreateDepartmentsDataTable()); MiniExcel.SaveAs("multi-sheet.xlsx", dataSet); ``` -------------------------------- ### Configure Shared String Cache Size Source: https://github.com/mini-software/miniexcel/blob/master/README.zh-CN.md Adjusts the threshold size for Shared Strings before disk-based caching is enabled. This allows fine-tuning memory usage versus performance for large files. ```csharp var config = new OpenXmlConfiguration { SharedStringCacheSize=500*1024*1024 }; MiniExcel.Query(path, configuration: config); ``` -------------------------------- ### Batch Add/Insert Pictures Source: https://github.com/mini-software/miniexcel/blob/master/README.zh-CN.md Add multiple pictures to an Excel file using `MiniExcel.AddPicture`. It's recommended to add pictures before generating row data to avoid high memory usage. ```csharp var images = new[] { new MiniExcelPicture { ImageBytes = File.ReadAllBytes(PathHelper.GetFile("images/github_logo.png")), SheetName = null, // default null is first sheet CellAddress = "C3", // required }, new MiniExcelPicture { ImageBytes = File.ReadAllBytes(PathHelper.GetFile("images/google_logo.png")), PictureType = "image/png", // default PictureType = image/png SheetName = "Demo", CellAddress = "C9", // required WidthPx = 100, HeightPx = 100, }, }; MiniExcel.AddPicture(path, images); ``` -------------------------------- ### Configure CSV Reading Empty String as Null Source: https://github.com/mini-software/miniexcel/blob/master/README.md Set `ReadEmptyStringAsNull` to `true` in `CsvConfiguration` to map empty values to null instead of string.Empty. ```csharp var config = new MiniExcelLibs.Csv.CsvConfiguration() { ReadEmptyStringAsNull = true }; ``` -------------------------------- ### Customize Excel Columns with Attributes Source: https://context7.com/mini-software/miniexcel/llms.txt Use attributes like ExcelColumnName, ExcelColumnWidth, ExcelColumnIndex, ExcelFormat, and ExcelIgnore to control how data is mapped and displayed in Excel. Supports multiple name mappings with Aliases. ```csharp using MiniExcelLibs; using MiniExcelLibs.Attributes; public class Employee { [ExcelColumnName("Employee ID")] // Custom header name public int Id { get; set; } [ExcelColumnName("Full Name")] [ExcelColumnWidth(25)] // Set column width public string Name { get; set; } [ExcelColumnIndex(5)] // Force column position (0-based) public string Department { get; set; } [ExcelFormat("yyyy-MM-dd")] // Date format public DateTime HireDate { get; set; } [ExcelFormat("#,#0.00")] // Number format public decimal Salary { get; set; } [ExcelIgnore] // Exclude from export public string InternalNotes { get; set; } [ExcelColumnName("EmpNo", Aliases = new[] { "EmployeeNumber", "No" })] // Multiple name mapping public string EmployeeNumber { get; set; } } // Using combined attribute public class Product { [ExcelColumn(Name = "Product ID", Index = 0)] public string Id { get; set; } [ExcelColumn(Name = "Created", Index = 1, Format = "yyyy-MM-dd", Width = 15)] public DateTime CreatedDate { get; set; } } // Export with attributes applied var employees = new List { /* ... */ }; MiniExcel.SaveAs("employees.xlsx", employees); // Query with attribute mapping var importedEmployees = MiniExcel.Query("employees.xlsx").ToList(); ``` -------------------------------- ### Query All Sheet Names and Rows Source: https://github.com/mini-software/miniexcel/blob/master/README.md Retrieve all sheet names from an Excel file and then query rows from each sheet. ```csharp var sheetNames = MiniExcel.GetSheetNames(path); foreach (var sheetName in sheetNames) { var rows = MiniExcel.Query(path, sheetName: sheetName); } ``` -------------------------------- ### Set Dynamic Sheet Attributes Source: https://github.com/mini-software/miniexcel/blob/master/README.md Configure sheet names and visibility dynamically using OpenXmlConfiguration. Useful for generating reports with multiple sheets. ```csharp var configuration = new OpenXmlConfiguration { DynamicSheets = new DynamicExcelSheet[] { new DynamicExcelSheet("usersSheet") { Name = "Users", State = SheetState.Visible }, new DynamicExcelSheet("departmentSheet") { Name = "Departments", State = SheetState.Hidden } } }; var users = new[] { new { Name = "Jack", Age = 25 }, new { Name = "Mike", Age = 44 } }; var department = new[] { new { ID = "01", Name = "HR" }, new { ID = "02", Name = "IT" } }; var sheets = new Dictionary { ["usersSheet"] = users, ["departmentSheet"] = department }; var path = PathHelper.GetTempPath(); MiniExcel.SaveAs(path, sheets, configuration: configuration); ``` -------------------------------- ### Conditional Statements in Template Cells Source: https://github.com/mini-software/miniexcel/blob/master/README.md Illustrates how to use if/elseif/else statements within template cells for dynamic content generation. Supports comparisons for DateTime, Double, Int, and String types. ```csharp @if(name == Jack) {{ employees.name }} @elseif(name == Neo) Test {{employees.name}} @else {{employees.department}} @endif ``` -------------------------------- ### Query Excel to Strongly Typed IEnumerable Source: https://github.com/mini-software/miniexcel/blob/master/README.md Execute a query and map the results to a strongly typed IEnumerable. Recommended to use Stream.Query for better efficiency. Ensure the UserAccount class properties match the Excel column names. ```csharp public class UserAccount { public Guid ID { get; set; } public string Name { get; set; } public DateTime BoD { get; set; } public int Age { get; set; } public bool VIP { get; set; } public decimal Points { get; set; } } var rows = MiniExcel.Query(path); // or using (var stream = File.OpenRead(path)) var rows = stream.Query(); ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.