Web Analytics

MiniExcel

⭐ 3234 stars Portuguese by mini-software

NuGet Build status star GitHub stars version Ask DeepWiki


Este projeto faz parte da .NET Foundation e opera sob o seu código de conduta.


English | 简体中文 | 繁體中文 | 日本語 | 한국어 | हिन्दी | ไทย | Français | Deutsch | Español | Italiano | Русский | Português | Nederlands | Polski | العربية | فارسی | Türkçe | Tiếng Việt | Bahasa Indonesia


Suas Stars ou Doações podem tornar o MiniExcel melhor


Introdução

MiniExcel é uma ferramenta simples e eficiente para processamento de Excel no .NET, projetada especificamente para minimizar o uso de memória.

Atualmente, a maioria dos frameworks populares precisa carregar todos os dados de um documento Excel na memória para facilitar as operações, mas isso pode causar problemas de consumo de memória. A abordagem do MiniExcel é diferente: os dados são processados linha por linha em modo streaming, reduzindo o consumo original de centenas de megabytes para apenas alguns megabytes, evitando efetivamente problemas de estouro de memória (OOM).

flowchart LR
    A1(["Excel analysis
process"]) --> A2{{"Unzipping
XLSX file"}} --> A3{{"Parsing
OpenXML"}} --> A4{{"Model
conversion"}} --> A5(["Output"])

B1(["Other Excel
Frameworks"]) --> B2{{"Memory"}} --> B3{{"Memory"}} --> B4{{"Workbooks &
Worksheets"}} --> B5(["All rows at
the same time"])

C1(["MiniExcel"]) --> C2{{"Stream"}} --> C3{{"Stream"}} --> C4{{"POCO or dynamic"}} --> C5(["Deferred execution
row by row"])

classDef analysis fill:#D0E8FF,stroke:#1E88E5,color:#0D47A1,font-weight:bold; classDef others fill:#FCE4EC,stroke:#EC407A,color:#880E4F,font-weight:bold; classDef miniexcel fill:#E8F5E9,stroke:#388E3C,color:#1B5E20,font-weight:bold;

class A1,A2,A3,A4,A5 analysis; class B1,B2,B3,B4,B5 others; class C1,C2,C3,C4,C5 miniexcel;

Funcionalidades

Versão 2.0 preview

Estamos trabalhando em uma futura versão do MiniExcel, com uma nova API modular e focada, pacotes nuget separados para funcionalidades Core e Csv, suporte completo para consultas transmitidas de forma assíncrona via IAsyncEnumerable, e mais novidades em breve! Os pacotes estarão disponíveis em pré-lançamento, então fique à vontade para experimentar e nos dar um feedback!

Se fizer isso, não deixe de conferir também a nova documentação e as notas de atualização.

Primeiros Passos

Instalação

Você pode instalar o pacote via NuGet

Notas de Lançamento

Por favor, confira as Notas de Lançamento

TODO

Por favor, verifique TODO

Desempenho

O código dos benchmarks pode ser encontrado em MiniExcel.Benchmarks.

O arquivo utilizado para testar o desempenho é Test1,000,000x10.xlsx, um documento de 32MB contendo 1.000.000 de linhas * 10 colunas cujas células estão preenchidas com a string "HelloWorld".

Para rodar todos os benchmarks, use:

dotnet run -project .\benchmarks\MiniExcel.Benchmarks -c Release -f net9.0 -filter * --join
Você pode encontrar os resultados dos benchmarks para a versão mais recente aqui.

Consulta/Importação do Excel

#### 1. Execute uma consulta e mapeie os resultados para um IEnumerable fortemente tipado [[Experimente]](https://dotnetfiddle.net/w5WD1J)

Recomenda-se usar Stream.Query devido à melhor eficiência.

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();

image

#### 2. Execute uma consulta e mapeie para uma lista de objetos dinâmicos sem usar head [[Experimente]](https://dotnetfiddle.net/w5WD1J)

| MiniExcel | 1 | |-----------|---| | Github | 2 |


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); }

#### 3. Execute uma consulta com a primeira linha como cabeçalho [[Experimente]](https://dotnetfiddle.net/w5WD1J)

nota : nomes de coluna iguais usam o último à direita

Entrada Excel :

| Coluna1 | Coluna2 | |-----------|---------| | MiniExcel | 1 | | Github | 2 |


var rows = MiniExcel.Query(useHeaderRow:true).ToList();

// or

using (var stream = File.OpenRead(path)) { var rows = stream.Query(useHeaderRow:true).ToList();

Assert.Equal("MiniExcel", rows[0].Column1); Assert.Equal(1, rows[0].Column2); Assert.Equal("Github", rows[1].Column1); Assert.Equal(2, rows[1].Column2); }

#### 4. Suporte a Consultas Extensão LINQ First/Take/Skip ...etc

Consulta First

var row = MiniExcel.Query(path).First();
Assert.Equal("HelloWorld", row.A);

// or

using (var stream = File.OpenRead(path)) { var row = stream.Query().First(); Assert.Equal("HelloWorld", row.A); }

Desempenho entre MiniExcel/ExcelDataReader/ClosedXML/EPPlus queryfirst

#### 5. Consulta por nome da planilha

MiniExcel.Query(path, sheetName: "SheetName");
//or
stream.Query(sheetName: "SheetName");
#### 6. Consultar todos os nomes de planilha e linhas

var sheetNames = MiniExcel.GetSheetNames(path);
foreach (var sheetName in sheetNames)
{
    var rows = MiniExcel.Query(path, sheetName: sheetName);
}
#### 7. Obter Colunas

var columns = MiniExcel.GetColumns(path); // e.g result : ["A","B"...]

var cnt = columns.Count; // get column count

#### 8. Consulta dinâmica converte linha para IDictionary

foreach(IDictionary row in MiniExcel.Query(path))
{
    //..
}

// or var rows = MiniExcel.Query(path).Cast>(); // or Query specified ranges (capitalized) // A2 represents the second row of column A, C3 represents the third row of column C // If you don't want to restrict rows, just don't include numbers var rows = MiniExcel.QueryRange(path, startCell: "A2", endCell: "C3").Cast>();

#### 9. Consultar Excel retornando DataTable

Não recomendado, pois o DataTable irá carregar todos os dados na memória e perderá o recurso de baixo consumo de memória do MiniExcel.

``C# var table = MiniExcel.QueryAsDataTable(path, useHeaderRow: true);

image

#### 10. Especifique a célula para começar a ler os dados

csharp MiniExcel.Query(path,useHeaderRow:true,startCell:"B3")
image

#### 11. Preencher Células Mescladas

Nota: A eficiência é menor em comparação com não usar preenchimento de mesclagem

Motivo: O padrão OpenXml coloca mergeCells no final do arquivo, o que leva à necessidade de percorrer o sheetxml duas vezes

csharp var config = new OpenXmlConfiguration() { FillMergedCells = true }; var rows = MiniExcel.Query(path, configuration: config);
image

suporta preenchimento de múltiplas linhas e colunas com comprimento e largura variáveis

image

#### 12. Leitura de arquivos grandes por cache baseado em disco (Disk-Base Cache - SharedString)

Se o tamanho de SharedStrings exceder 5 MB, o MiniExcel usará por padrão o cache em disco local, por exemplo, 10x100000.xlsx (um milhão de linhas de dados), ao desabilitar o cache em disco o uso máximo de memória é de 195MB, mas com o cache em disco habilitado são necessários apenas 65MB. Observe que essa otimização tem um custo de eficiência, então neste caso o tempo de leitura aumentará de 7,4 segundos para 27,2 segundos. Se você não precisar disso, pode desabilitar o cache em disco com o seguinte código:

csharp var config = new OpenXmlConfiguration { EnableSharedStringCache = false }; MiniExcel.Query(path,configuration: config)
Você pode usar SharedStringCacheSize para alterar o tamanho do arquivo sharedString além do tamanho especificado para cache em disco
csharp var config = new OpenXmlConfiguration { SharedStringCacheSize=50010241024 }; MiniExcel.Query(path, configuration: config);
image

image

Criar/Exportar Excel

  • Deve ser um tipo não abstrato com um construtor público sem parâmetros.
  • O MiniExcel suporta execução adiada de parâmetro IEnumerable. Se você deseja usar menos memória, por favor, não chame métodos como ToList
exemplo: ToList ou não uso de memória image

#### 1. Anônimo ou fortemente tipado [[Experimente]](https://dotnetfiddle.net/w5WD1J)

csharp var path = Path.Combine(Path.GetTempPath(), $"{Guid.NewGuid()}.xlsx"); MiniExcel.SaveAs(path, new[] { new { Column1 = "MiniExcel", Column2 = 1 }, new { Column1 = "Github", Column2 = 2} });
#### 2. IEnumerable>

csharp var values = new List>() { new Dictionary{{ "Column1", "MiniExcel" }, { "Column2", 1 } }, new Dictionary{{ "Column1", "Github" }, { "Column2", 2 } } }; MiniExcel.SaveAs(path, values);
Criar Resultado do Arquivo :

| Coluna1 | Coluna2 | |-----------|---------| | MiniExcel | 1 | | Github | 2 |

#### 3. IDataReader

  • Recomendado, pode evitar carregar todos os dados na memória
csharp MiniExcel.SaveAs(path, reader);
image

Exportação de múltiplas planilhas pelo DataReader (recomendado pelo Dapper ExecuteReader)

csharp using (var cnn = Connection) { cnn.Open(); var sheets = new Dictionary(); sheets.Add("sheet1", cnn.ExecuteReader("select 1 id")); sheets.Add("sheet2", cnn.ExecuteReader("select 2 id")); MiniExcel.SaveAs("Demo.xlsx", sheets); }
#### 4. Datatable

  • Não recomendado, irá carregar todos os dados na memória
  • DataTable usa Caption como nome da coluna primeiro, depois usa columname
csharp var path = Path.Combine(Path.GetTempPath(), $"{Guid.NewGuid()}.xlsx"); var table = new DataTable(); { table.Columns.Add("Column1", typeof(string)); table.Columns.Add("Column2", typeof(decimal)); table.Rows.Add("MiniExcel", 1); table.Rows.Add("Github", 2); }

MiniExcel.SaveAs(path, table);

#### 5. Consulta Dapper

Obrigado @shaofing #552, por favor use CommandDefinition + CommandFlags.NoCache

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); }
O código abaixo carregará todos os dados na memória

csharp using (var connection = GetConnection(connectionString)) { var rows = connection.Query(@"select 'MiniExcel' as Column1,1 as Column2 union all select 'Github',2"); MiniExcel.SaveAs(path, rows); }
#### 6. SaveAs para MemoryStream  [[Experimente]](https://dotnetfiddle.net/JOen0e)

csharp using (var stream = new MemoryStream()) //support FileStream,MemoryStream ect. { stream.SaveAs(values); }
por exemplo: API de exportação para Excel

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" }; }

#### 7. Criar Múltiplas Planilhas

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);

// 2. DataSet var sheets = new DataSet(); sheets.Add(UsersDataTable); sheets.Add(DepartmentDataTable); //.. MiniExcel.SaveAs(path, sheets);

image

#### 8. Opções de TableStyles

Estilo padrão

image

Sem configuração de estilo

csharp var config = new OpenXmlConfiguration() { TableStyles = TableStyles.None }; MiniExcel.SaveAs(path, value,configuration:config);
image

#### 9. AutoFiltro

Desde a v0.19.0, OpenXmlConfiguration.AutoFilter pode ativar/desativar o AutoFiltro, o valor padrão é true, e a forma de configurar o AutoFiltro é:

csharp MiniExcel.SaveAs(path, value, configuration: new OpenXmlConfiguration() { AutoFilter = false });

#### 10. Criar Imagem

csharp var value = new[] { new { Name="github",Image=File.ReadAllBytes(PathHelper.GetFile("images/github_logo.png"))}, new { Name="google",Image=File.ReadAllBytes(PathHelper.GetFile("images/google_logo.png"))}, new { Name="microsoft",Image=File.ReadAllBytes(PathHelper.GetFile("images/microsoft_logo.png"))}, new { Name="reddit",Image=File.ReadAllBytes(PathHelper.GetFile("images/reddit_logo.png"))}, new { Name="statck_overflow",Image=File.ReadAllBytes(PathHelper.GetFile("images/statck_overflow_logo.png"))}, }; MiniExcel.SaveAs(path, value);
image

#### 11. Exportação de Arquivo como Byte Array

Desde a versão 1.22.0, quando o tipo de valor é byte[], o sistema salvará o caminho do arquivo na célula por padrão e, ao importar, o sistema pode converter para byte[]. E se você não quiser usar isso, pode definir OpenXmlConfiguration.EnableConvertByteArray como false, o que pode melhorar a eficiência do sistema.

image

Desde a versão 1.22.0, quando o tipo de valor é byte[], o sistema salvará o caminho do arquivo na célula por padrão e, ao importar, o sistema pode converter para byte[]. E se você não quiser usar isso, pode definir OpenXmlConfiguration.EnableConvertByteArray como false, o que pode melhorar a eficiência do sistema.

image

#### 12. Mesclar células iguais verticalmente

Esta funcionalidade é suportada apenas no formato xlsx e mescla as células verticalmente entre as tags @merge e @endmerge. Você pode usar @mergelimit para limitar os limites da mesclagem de células verticalmente.

csharp var mergedFilePath = Path.Combine(Path.GetTempPath(), $"{Guid.NewGuid().ToString()}.xlsx");

var path = @"../../../../../samples/xlsx/TestMergeWithTag.xlsx";

MiniExcel.MergeSameCells(mergedFilePath, path);

csharp var memoryStream = new MemoryStream();

var path = @"../../../../../samples/xlsx/TestMergeWithTag.xlsx";

memoryStream.MergeSameCells(path);

Conteúdo do arquivo antes e depois da mesclagem:

Sem limite de mesclagem:

Screenshot 2023-08-07 at 11 59 24

Screenshot 2023-08-07 at 11 59 57

Com limite de mesclagem:

Screenshot 2023-08-08 at 18 21 00

Screenshot 2023-08-08 at 18 21 40

#### 13. Pular valores nulos

Nova opção explícita para gravar células vazias para valores nulos:

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);

imagem

xml Somebody once told me.

Comportamento anterior:

csharp / ... /

OpenXmlConfiguration configuration = new OpenXmlConfiguration() { EnableWriteNullValueCell = false // Default value is true. };

MiniExcel.SaveAs(@"C:\temp\Book1.xlsx", dt, configuration: configuration);

imagem

xml Somebody once told me.
Funciona para valores nulos e DBNull.

#### 14. Congelar Painéis

csharp / ... /

OpenXmlConfiguration configuration = new OpenXmlConfiguration() { FreezeRowCount = 1, // default is 1 FreezeColumnCount = 2 // default is 0 };

MiniExcel.SaveAs(@"C:\temp\Book1.xlsx", dt, configuration: configuration);

image

Preencher Dados em Modelo do Excel

  • A declaração é semelhante ao template Vue {{nome da variável}}, ou a renderização de coleção {{nome da coleção.nome do campo}}
  • A renderização de coleção suporta IEnumerable/DataTable/DapperRow
#### 1. Preenchimento Básico

Modelo: image

Resultado: image

Código:

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);

#### 2. Preenchimento de Dados IEnumerable

Nota1: Use o primeiro IEnumerable da mesma coluna como base para preencher a lista

Modelo: image

Resultado: image

Código:

csharp //1. By POCO var value = new { employees = new[] { new {name="Jack",department="HR"}, new {name="Lisa",department="HR"}, new {name="John",department="HR"}, new {name="Mike",department="IT"}, new {name="Neo",department="IT"}, new {name="Loan",department="IT"} } }; MiniExcel.SaveAsByTemplate(path, templatePath, value);

//2. By Dictionary var value = new Dictionary() { ["employees"] = new[] { new {name="Jack",department="HR"}, new {name="Lisa",department="HR"}, new {name="John",department="HR"}, new {name="Mike",department="IT"}, new {name="Neo",department="IT"}, new {name="Loan",department="IT"} } }; MiniExcel.SaveAsByTemplate(path, templatePath, value);

#### 3. Preenchimento de Dados Complexos

Nota: Suporta múltiplas planilhas e uso da mesma variável

Modelo:

image

Resultado:

image

csharp // 1. By POCO var value = new { 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"} } }; MiniExcel.SaveAsByTemplate(path, templatePath, value);

// 2. By Dictionary var 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"} } }; MiniExcel.SaveAsByTemplate(path, templatePath, value);

#### 4. Preenchimento de Desempenho com Big Data

NOTA: Usar execução adiada IEnumerable em vez de ToList pode economizar o uso máximo de memória no MiniExcel

imagem

#### 5. Mapeamento automático de tipo do valor da célula

Modelo

imagem

Resultado

imagem

Classe

csharp public class Poco { public string @string { get; set; } public int? @int { get; set; } public decimal? @decimal { get; set; } public double? @double { get; set; } public DateTime? datetime { get; set; } public bool? @bool { get; set; } public Guid? Guid { get; set; } }
Código

csharp var poco = new TestIEnumerableTypePoco { @string = "string", @int = 123, @decimal = decimal.Parse("123.45"), @double = (double)123.33, @datetime = new DateTime(2021, 4, 1), @bool = true, @Guid = Guid.NewGuid() }; var value = new { Ts = new[] { poco, new TestIEnumerableTypePoco{}, null, poco } }; MiniExcel.SaveAsByTemplate(path, templatePath, value);
#### 6. Exemplo :  Listar Projetos do Github

Modelo

image

Resultado

image

Código

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);
#### 7. Preenchimento de Dados Agrupados

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);
##### 1. Com a tag @group e com a tag @header

Antes

before_with_header

Depois

after_with_header

##### 2. Com a tag @group e sem a tag @header

Antes

before_without_header

Depois

after_without_header

##### 3. Sem a tag @group

Antes

without_group

Depois

without_group_after

#### 8. Declarações If/ElseIf/Else dentro da célula

Regras:

  • Suporta DateTime, Double, Int com os operadores ==, !=, >, >=, <, <=.
  • Suporta String com os operadores ==, !=.
  • Cada declaração deve estar em uma nova linha.
  • Deve ser adicionado um espaço simples antes e depois dos operadores.
  • Não deve haver nova linha dentro das declarações.
  • A célula deve estar exatamente no formato abaixo.
csharp @if(name == Jack) {{employees.name}} @elseif(name == Neo) Test {{employees.name}} @else {{employees.department}} @endif
Antes

if_before

Depois

if_after

#### 9. DataTable como parâmetro

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);
#### 10. Fórmulas

##### 1. Exemplo Prefixe sua fórmula com $ e use $enumrowstart e $enumrowend para marcar as referências ao início e ao fim das linhas enumeráveis:

image

Quando o template é renderizado, o prefixo $ será removido e $enumrowstart e $enumrowend serão substituídos pelos números das linhas inicial e final da enumeração:

image

##### 2. Outras Fórmulas de Exemplo:

| | | |--------------|-------------------------------------------------------------------------------------------| | Soma | $=SUM(C{{$enumrowstart}}:C{{$enumrowend}}) | | Média Alter. | $=SUM(C{{$enumrowstart}}:C{{$enumrowend}}) / COUNT(C{{$enumrowstart}}:C{{$enumrowend}}) | | Intervalo | $=MAX(C{{$enumrowstart}}:C{{$enumrowend}}) - MIN(C{{$enumrowstart}}:C{{$enumrowend}}) |

#### 11. Outros

##### 1. Verificando a chave de parâmetro do template

Desde a versão V1.24.0, por padrão, a ausência de parâmetros no template é ignorada e substituída por string vazia. IgnoreTemplateParameterMissing pode controlar se uma exceção será lançada ou não.

csharp var config = new OpenXmlConfiguration() { IgnoreTemplateParameterMissing = false, }; MiniExcel.SaveAsByTemplate(path, templatePath, value, config)
image

Nome da Coluna do Excel/Índice/Ignorar Atributo

#### 1. Especificar o nome da coluna, índice da coluna, ignorar coluna

Exemplo de Excel

image

Código

csharp public class ExcelAttributeDemo { [ExcelColumnName("Column1")] public string Test1 { get; set; } [ExcelColumnName("Column2")] public string Test2 { get; set; } [ExcelIgnore] public string Test3 { get; set; } [ExcelColumnIndex("I")] // system will convert "I" to 8 index public string Test4 { get; set; } public string Test5 { get; } //wihout set will ignore public string Test6 { get; private set; } //un-public set will ignore [ExcelColumnIndex(3)] // start with 0 public string Test7 { get; set; } }

var rows = MiniExcel.Query(path).ToList(); Assert.Equal("Column1", rows[0].Test1); Assert.Equal("Column2", rows[0].Test2); Assert.Null(rows[0].Test3); Assert.Equal("Test7", rows[0].Test4); Assert.Null(rows[0].Test5); Assert.Null(rows[0].Test6); Assert.Equal("Test4", rows[0].Test7);

#### 2. Formato Personalizado (ExcelFormatAttribute)

Desde a versão V0.21.0, suporta classe que contém o método ToString(string content) para formatação

Classe

csharp public class Dto { public string Name { get; set; }

[ExcelFormat("MMMM dd, yyyy")] public DateTime InDate { get; set; } }

Código

csharp var value = new Dto[] { new Issue241Dto{ Name="Jack",InDate=new DateTime(2021,01,04)}, new Issue241Dto{ Name="Henry",InDate=new DateTime(2020,04,05)}, }; MiniExcel.SaveAs(path, value);
Resultado

image

Consulta suporta conversão de formato personalizada

image

#### 3. Definir Largura da Coluna(ExcelColumnWidthAttribute)

csharp public class Dto { [ExcelColumnWidth(20)] public int ID { get; set; } [ExcelColumnWidth(15.50)] public string Name { get; set; } }
#### 4. Vários nomes de colunas mapeando para a mesma propriedade.

csharp public class Dto { [ExcelColumnName(excelColumnName:"EmployeeNo",aliases:new[] { "EmpNo","No" })] public string Empno { get; set; } public string Name { get; set; } }
#### 5. System.ComponentModel.DisplayNameAttribute = ExcelColumnName.excelColumnNameAttribute

Desde a versão 1.24.0, o sistema suporta System.ComponentModel.DisplayNameAttribute = ExcelColumnName.excelColumnNameAttribute

C# public class TestIssueI4TXGTDto { public int ID { get; set; } public string Name { get; set; } [DisplayName("Specification")] public string Spc { get; set; } [DisplayName("Unit Price")] public decimal Up { get; set; } }

#### 6. ExcelColumnAttribute

Desde a versão V1.26.0, vários atributos podem ser simplificados assim :

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; } }
#### 7. DynamicColumnAttribute

Desde a versão V1.26.0, podemos definir dinamicamente os atributos da Coluna

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);
image

#### 8. DynamicSheetAttribute

Desde a versão V1.31.4, podemos definir os atributos da Sheet dinamicamente. Podemos definir o nome da planilha e o estado (visibilidade).

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);

Podemos também usar o novo atributo ExcelSheetAttribute:

C# [ExcelSheet(Name = "Departments", State = SheetState.Hidden)] private class DepartmentDto { [ExcelColumn(Name = "ID",Index = 0)] public string ID { get; set; } [ExcelColumn(Name = "Name",Index = 1)] public string Name { get; set; } }
### Adicionar, Excluir, Atualizar

#### Adicionar

v1.28.0 suporta inserção de N linhas de dados em CSV após a última linha

csharp // Origin { var value = new[] { new { ID=1,Name ="Jack",InDate=new DateTime(2021,01,03)}, new { ID=2,Name ="Henry",InDate=new DateTime(2020,05,03)}, }; MiniExcel.SaveAs(path, value); } // Insert 1 rows after last { var value = new { ID=3,Name = "Mike", InDate = new DateTime(2021, 04, 23) }; MiniExcel.Insert(path, value); } // Insert N rows after last { var value = new[] { new { ID=4,Name ="Frank",InDate=new DateTime(2021,06,07)}, new { ID=5,Name ="Gloria",InDate=new DateTime(2022,05,03)}, }; MiniExcel.Insert(path, value); }
image

v1.37.0 suporta a inserção de uma nova planilha em uma pasta de trabalho existente

csharp // Origin excel { var value = new[] { new { ID=1,Name ="Jack",InDate=new DateTime(2021,01,03)}, new { ID=2,Name ="Henry",InDate=new DateTime(2020,05,03)}, }; MiniExcel.SaveAs(path, value, sheetName: "Sheet1"); } // Insert a new sheet { var value = new { ID=3,Name = "Mike", InDate = new DateTime(2021, 04, 23) }; MiniExcel.Insert(path, table, sheetName: "Sheet2"); }
#### Excluir(aguardando)

#### Atualizar(aguardando)

Verificação Automática do Tipo de Excel

  • O MiniExcel verificará se é xlsx ou csv com base na extensão do arquivo por padrão, mas pode haver imprecisão, por favor, especifique manualmente.
  • Não é possível saber de qual excel o Stream vem, por favor, especifique manualmente.
csharp stream.SaveAs(excelType:ExcelType.CSV); //or stream.SaveAs(excelType:ExcelType.XLSX); //or stream.Query(excelType:ExcelType.CSV); //or stream.Query(excelType:ExcelType.XLSX);

CSV

#### Nota

  • O retorno padrão é do tipo string, e o valor não será convertido para números ou datetime, a menos que o tipo seja definido por tipagem forte genérica.
#### Separador personalizado

O padrão é , como separador, você pode modificar a propriedade Seperator para personalização

csharp var config = new MiniExcelLibs.Csv.CsvConfiguration() { Seperator=';' }; MiniExcel.SaveAs(path, values,configuration: config);
Desde a versão V1.30.1 há suporte para função de separador personalizado (agradecimentos ao @hyzx86)

csharp var config = new CsvConfiguration() { SplitFn = (row) => Regex.Split(row, $"\"" target="_blank" rel="noopener noreferrer">\t,$)") .Select(s => Regex.Replace(s.Replace("\"\"", "\""), "^\"|\"$", "")).ToArray() }; var rows = MiniExcel.Query(path, configuration: config).ToList();
#### Quebra de linha personalizada

O padrão é \r\n como o caractere de nova linha, você pode modificar a propriedade NewLine para personalização

csharp var config = new MiniExcelLibs.Csv.CsvConfiguration() { NewLine='\n' }; MiniExcel.SaveAs(path, values,configuration: config);
#### Codificação personalizada

  • A codificação padrão é "Detectar Codificação a partir de Byte Order Marks" (detectEncodingFromByteOrderMarks: true)
  • Se você tiver requisitos de codificação personalizados, por favor modifique a propriedade StreamReaderFunc / StreamWriterFunc
csharp // Read var config = new MiniExcelLibs.Csv.CsvConfiguration() { StreamReaderFunc = (stream) => new StreamReader(stream,Encoding.GetEncoding("gb2312")) }; var rows = MiniExcel.Query(path, true,excelType:ExcelType.CSV,configuration: config);

// Write var config = new MiniExcelLibs.Csv.CsvConfiguration() { StreamWriterFunc = (stream) => new StreamWriter(stream, Encoding.GetEncoding("gb2312")) }; MiniExcel.SaveAs(path, value,excelType:ExcelType.CSV, configuration: config);

#### Ler string vazia como nulo

Por padrão, valores vazios são mapeados para string.Empty. Você pode modificar esse comportamento

csharp var config = new MiniExcelLibs.Csv.CsvConfiguration() { ReadEmptyStringAsNull = true };
### DataReader

#### 1. GetReader Desde a versão 1.23.0, você pode usar GetDataReader

csharp using (var reader = MiniExcel.GetReader(path,true)) { while (reader.Read()) { for (int i = 0; i < reader.FieldCount; i++) { var value = reader.GetValue(i); } } }

Assíncrono

  • v0.17.0 suporta Assíncrono (agradecimentos a isdaniel ( SHIH,BING-SIOU)](https://github.com/isdaniel))
csharp public static Task SaveAsAsync(string path, object value, bool printHeader = true, string sheetName = "Sheet1", ExcelType excelType = ExcelType.UNKNOWN, IConfiguration configuration = null) public static Task SaveAsAsync(this Stream stream, object value, bool printHeader = true, string sheetName = "Sheet1", ExcelType excelType = ExcelType.XLSX, IConfiguration configuration = null) public static Task> QueryAsync(string path, bool useHeaderRow = false, string sheetName = null, ExcelType excelType = ExcelType.UNKNOWN, string startCell = "A1", IConfiguration configuration = null) public static Task> QueryAsync(this Stream stream, string sheetName = null, ExcelType excelType = ExcelType.UNKNOWN, string startCell = "A1", IConfiguration configuration = null) where T : class, new() public static Task> QueryAsync(string path, string sheetName = null, ExcelType excelType = ExcelType.UNKNOWN, string startCell = "A1", IConfiguration configuration = null) where T : class, new() public static Task>> QueryAsync(this Stream stream, bool useHeaderRow = false, string sheetName = null, ExcelType excelType = ExcelType.UNKNOWN, string startCell = "A1", IConfiguration configuration = null) public static Task SaveAsByTemplateAsync(this Stream stream, string templatePath, object value) public static Task SaveAsByTemplateAsync(this Stream stream, byte[] templateBytes, object value) public static Task SaveAsByTemplateAsync(string path, string templatePath, object value) public static Task SaveAsByTemplateAsync(string path, byte[] templateBytes, object value) public static Task QueryAsDataTableAsync(string path, bool useHeaderRow = true, string sheetName = null, ExcelType excelType = ExcelType.UNKNOWN, string startCell = "A1", IConfiguration configuration = null)
-  v1.25.0 suporta cancellationToken

Outros

#### 1. Enum

Certifique-se de que o nome no excel e o nome da propriedade sejam iguais, o sistema fará o mapeamento automático (não diferencia maiúsculas de minúsculas)

image

Desde a V0.18.0 suporta Descrição de Enum

csharp public class Dto { public string Name { get; set; } public I49RYZUserType UserType { get; set; } }

public enum Type { [Description("General User")] V1, [Description("General Administrator")] V2, [Description("Super Administrator")] V3 }

image

Desde a versão 1.30.0 há suporte para Descrição do Excel para Enum, obrigado @KaneLeung

#### 2. Converter CSV para XLSX ou Converter XLSX para CSV

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);
}
#### 3. CultureInfo Personalizado

Desde a versão 1.22.0, você pode personalizar o CultureInfo conforme abaixo, sendo o padrão do sistema CultureInfo.InvariantCulture.

var config = new CsvConfiguration()
{
    Culture = new CultureInfo("fr-FR"),
};
MiniExcel.SaveAs(path, value, configuration: config);

// or MiniExcel.Query(path, configuration: config);

#### 4. Tamanho Personalizado do Buffer

    public abstract class Configuration : IConfiguration
    {
        public int BufferSize { get; set; } = 1024 * 512;
    }
#### 5. ModoRápido

O sistema não irá controlar a memória, mas você pode obter uma velocidade de salvamento mais rápida.

var config = new OpenXmlConfiguration() { FastMode = true };
MiniExcel.SaveAs(path, reader,configuration:config);
#### 6. Adicionar Imagem em Lote (MiniExcel.AddPicture)

Por favor, adicione as imagens antes de gerar os dados das linhas em lote, ou o sistema irá usar muita memória ao chamar AddPicture.

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);
Imagem

#### 7. Obter Dimensão das Planilhas

var dim = MiniExcel.GetSheetDimensions(path);

Exemplos:

#### 1. SQLite & Dapper Arquivo de Grande Tamanho Inserção SQL Evite OOM

nota: por favor, não chame os métodos ToList/ToArray após Query, isso irá carregar todos os dados na memória

using (var connection = new SQLiteConnection(connectionString))
{
    connection.Open();
    using (var transaction = connection.BeginTransaction())
    using (var stream = File.OpenRead(path))
    {
       var rows = stream.Query();
       foreach (var row in rows)
             connection.Execute("insert into T (A,B) values (@A,@B)", new { row.A, row.B }, transaction: transaction);
       transaction.Commit();
    }
}
desempenho: image

#### 2. Demonstração da API ASP.NET Core 3.1 ou MVC 5 Download/Upload Excel Xlsx Experimente

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"); } }

#### 3. Consulta de Paginação

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); }

20210419

#### 4. Exportação de Excel em WebForm por memorystream

var fileName = "Demo.xlsx";
var sheetName = "Sheet1";
HttpResponse response = HttpContext.Current.Response;
response.Clear();
response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
response.AddHeader("Content-Disposition", $"attachment;filename=\"{fileName}\"");
var values = new[] {
    new { Column1 = "MiniExcel", Column2 = 1 },
    new { Column1 = "Github", Column2 = 2}
};
var memoryStream = new MemoryStream();
memoryStream.SaveAs(values, sheetName: sheetName);
memoryStream.Seek(0, SeekOrigin.Begin);
memoryStream.CopyTo(Response.OutputStream);
response.End();

#### 5. Gerenciamento dinâmico de i18n multilíngue e autoridade de função

Como no exemplo, crie um método para lidar com i18n e gerenciamento de permissões, e use yield return para retornar IEnumerable> para obter efeitos dinâmicos e de baixo consumo de memória

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; } }

image

FAQ

#### P: O título do cabeçalho do Excel não é igual ao nome da propriedade da classe, como mapear?

R. Por favor, utilize o atributo ExcelColumnName

image

#### P. Como consultar ou exportar múltiplas planilhas?

R. Método GetSheetNames com o parâmetro de sheetName na consulta.

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);
}
image

#### P. Como consultar ou exportar informações sobre a visibilidade das folhas?

R. Método GetSheetInformations.

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
}
#### P. Usar Count irá carregar todos os dados na memória?

Não, o teste de imagem possui 1 milhão de linhas*10 colunas de dados, o uso máximo de memória é <60MB, e leva 13,65 segundos

image

#### P. Como o Query usa índices inteiros?

O índice padrão do Query é a chave string: A,B,C.... Se você quiser mudar para índice numérico, por favor crie o seguinte método para converter

void Main()
{
    var path = @"D:\git\MiniExcel\samples\xlsx\TestTypeMapping.xlsx";
    var rows = MiniExcel.Query(path,true);
    foreach (var r in ConvertToIntIndexRows(rows))
    {
        Console.Write($"column 0 : {r[0]} ,column 1 : {r[1]}");
        Console.WriteLine();
    }
}

private IEnumerable> ConvertToIntIndexRows(IEnumerable rows) { ICollection keys = null; var isFirst = true; foreach (IDictionary r in rows) { if(isFirst) { keys = r.Keys; isFirst = false; }

var dic = new Dictionary(); var index = 0; foreach (var key in keys) dic[index++] = r[key]; yield return dic; } } #### P. Nenhum título, Excel vazio é gerado quando o valor está vazio ao exportar para Excel

Como o MiniExcel utiliza uma lógica semelhante ao JSON.NET para obter dinamicamente o tipo dos valores a fim de simplificar as operações da API, o tipo não pode ser conhecido sem dados. Você pode conferir issue #133 para entender.

image

Tipos fortes & DataTable irão gerar cabeçalhos, mas Dictionary ainda geram Excel vazio

#### P. Como parar o foreach quando encontrar uma linha em branco?

MiniExcel pode ser usado com LINQ TakeWhile para parar o iterador foreach.

Image

#### P. Como remover linhas vazias?

image

IEnumerable :

public static IEnumerable QueryWithoutEmptyRow(Stream stream, bool useHeaderRow, string sheetName, ExcelType excelType, string startCell, IConfiguration configuration)
{
    var rows = stream.Query(useHeaderRow,sheetName,excelType,startCell,configuration);
    foreach (IDictionary row in rows)
    {
        if(row.Keys.Any(key=>row[key]!=null))
            yield return row;
    }
}

DataTable :

public static DataTable QueryAsDataTableWithoutEmptyRow(Stream stream, bool useHeaderRow, string sheetName, ExcelType excelType, string startCell, IConfiguration configuration)
{
    if (sheetName == null && excelType != ExcelType.CSV) /Issue #279/
        sheetName = stream.GetSheetNames().First();

var dt = new DataTable(sheetName); var first = true; var rows = stream.Query(useHeaderRow,sheetName,excelType,startCell,configuration); foreach (IDictionary row in rows) { if (first) {

foreach (var key in row.Keys) { var column = new DataColumn(key, typeof(object)) { Caption = key }; dt.Columns.Add(column); }

dt.BeginLoadData(); first = false; }

var newRow = dt.NewRow(); var isNull=true; foreach (var key in row.Keys) { var _v = row[key]; if(_v!=null) isNull = false; newRow[key] = _v; }

if(!isNull) dt.Rows.Add(newRow); }

dt.EndLoadData(); return dt; }

#### P. Como SaveAs(path,value) pode substituir um arquivo existente sem lançar o erro "O arquivo ...xlsx já existe"

Por favor, utilize a classe Stream para personalizar a lógica de criação de arquivos, por exemplo:

`C# using (var stream = File.Create("Demo.xlsx")) MiniExcel.SaveAs(stream,value);

ou, desde a V1.25.0, o SaveAs suporta o parâmetro overwriteFile para habilitar/desabilitar a sobrescrição de arquivos existentes

csharp MiniExcel.SaveAs(path, value, overwriteFile: true); ``

Limitações e advertências

  • Atualmente não há suporte para xls e arquivos criptografados
  • xlsm suporta apenas Query

Referência

ExcelDataReader / ClosedXML / Dapper / ExcelNumberFormat

Agradecimentos

#### Jetbrains

jetbrains-variant-2

Agradecemos por fornecer um All product IDE gratuito para este projeto (Licença)

Compartilhamento de contribuição e doação

Link https://github.com/orgs/mini-software/discussions/754

Contribuidores

--- Tranlated By Open Ai Tx | Last indexed: 2025-10-09 ---