Como Adicionar ou Ler Fórmulas e Funções no Excel Usando Código C#
O Excel é um poderoso software de planilhas que oferece diversos recursos, entre os quais as fórmulas e funções estão entre os mais importantes. Elas permitem realizar diferentes operações matemáticas, estatísticas e lógicas nos dados, ajudando os usuários a obter informações relevantes de maneira rápida e precisa.
Neste artigo, vamos explicar como adicionar e ler fórmulas e funções em arquivos Excel usando código C# e VB.NET.
Instalar o Componente para .NET
Primeiro, é necessário adicionar os arquivos DLL incluídos no pacote do componente como referências ao projeto .NET. Os arquivos necessários podem ser baixados no site oficial ou instalados por meio do NuGet.
PM> Install-Package Spire.XLS
Adicionar Fórmulas e Funções ao Excel com C# e VB.NET
Para adicionar fórmulas ou funções a células específicas de uma planilha do Excel, você pode utilizar a propriedade Worksheet.Range[int row, int column].Formula.
As principais etapas são as seguintes:
- Inicialize uma instância da classe
Workbook. - Obtenha uma planilha específica pelo índice usando a propriedade
Workbook.Worksheets[int index]. - Adicione dados de texto e valores numéricos às células desejadas da planilha utilizando as propriedades
Worksheet.Range[int row, int column].TexteWorksheet.Range[int row, int column].NumberValue. - Adicione textos e fórmulas às células específicas utilizando as propriedades
Worksheet.Range[int row, int column].TexteWorksheet.Range[int row, int column].Formula. - Da mesma forma, utilize essas propriedades para adicionar textos e funções às células desejadas.
- Por fim, salve o arquivo resultante usando o método
Workbook.SaveToFile(string fileName, ExcelVersion version).
O código de exemplo completo é apresentado a seguir.
using Spire.Xls;
namespace AddFormulasAndFunctions
{
internal class Program
{
static void Main(string[] args)
{
// Inicializar uma instância da classe Workbook
Workbook workbook = new Workbook();
// Obter a primeira planilha
Worksheet sheet = workbook.Worksheets[0];
// Declarar duas variáveis: currentRow e currentFormula
int currentRow = 1;
string currentFormula;
// Adicionar texto à planilha e definir o estilo da célula
sheet.Range[currentRow, 1].Text = "Test Data:";
sheet.Range[currentRow, 1].Style.Font.IsBold = true;
sheet.Range[currentRow, 1].Style.FillPattern = ExcelPatternType.Solid;
sheet.Range[currentRow, 1].Style.KnownColor = ExcelColors.LightGreen1;
sheet.Range[currentRow, 1].Style.Borders[BordersLineType.EdgeBottom].LineStyle = LineStyleType.Medium;
// Adicionar dados numéricos à planilha
sheet.Range[++currentRow, 1].NumberValue = 7.3;
sheet.Range[currentRow, 2].NumberValue = 5;
sheet.Range[currentRow, 3].NumberValue = 8.2;
sheet.Range[currentRow, 4].NumberValue = 4;
sheet.Range[currentRow, 5].NumberValue = 3;
sheet.Range[currentRow, 6].NumberValue = 11.3;
currentRow++;
// Adicionar texto à planilha e definir o estilo das células
sheet.Range[++currentRow, 1].Text = "Formulas";
sheet.Range[currentRow, 2].Text = "Results";
sheet.Range[currentRow, 1, currentRow, 2].Style.Font.IsBold = true;
sheet.Range[currentRow, 1, currentRow, 2].Style.KnownColor = ExcelColors.LightGreen1;
sheet.Range[currentRow, 1, currentRow, 2].Style.FillPattern = ExcelPatternType.Solid;
sheet.Range[currentRow, 1, currentRow, 2].Style.Borders[BordersLineType.EdgeBottom].LineStyle = LineStyleType.Medium;
// Adicionar textos e fórmulas à planilha
currentFormula = "=\"Hello\"";
sheet.Range[++currentRow, 1].Text = "'" + currentFormula;
sheet.Range[currentRow, 2].Formula = currentFormula;
currentFormula = "=300";
sheet.Range[++currentRow, 1].Text = "'" + currentFormula;
sheet.Range[currentRow, 2].Formula = currentFormula;
currentFormula = "=3389.639421";
sheet.Range[++currentRow, 1].Text = "'" + currentFormula;
sheet.Range[currentRow, 2].Formula = currentFormula;
currentFormula = "=false";
sheet.Range[++currentRow, 1].Text = "'" + currentFormula;
sheet.Range[currentRow, 2].Formula = currentFormula;
currentFormula = "=1+2+3+4+5-6-7+8-9";
sheet.Range[++currentRow, 1].Text = "'" + currentFormula;
sheet.Range[currentRow, 2].Formula = currentFormula;
currentFormula = "=33*3/4-2+10";
sheet.Range[++currentRow, 1].Text = "'" + currentFormula;
sheet.Range[currentRow, 2].Formula = currentFormula;
currentFormula = "=Sheet1!$B$2";
sheet.Range[++currentRow, 1].Text = "'" + currentFormula;
sheet.Range[currentRow, 2].Formula = currentFormula;
// Adicionar textos e funções à planilha
// Função AVERAGE
currentFormula = "=AVERAGE(Sheet1!$D$2:F$2)";
sheet.Range[++currentRow, 1].Text = "'" + currentFormula;
sheet.Range[currentRow, 2].Formula = currentFormula;
// Função COUNT
currentFormula = "=COUNT(3,5,8,10,2,34)";
sheet.Range[++currentRow, 1].Text = "'" + currentFormula;
sheet.Range[currentRow, 2].Formula = currentFormula;
// Função NOW
currentFormula = "=NOW()";
sheet.Range[++currentRow, 1].Text = "'" + currentFormula;
sheet.Range[currentRow, 2].Formula = currentFormula;
sheet.Range[currentRow, 2].Style.NumberFormat = "yyyy-MM-DD";
// Função SECOND
currentFormula = "=SECOND(0.503)";
sheet.Range[++currentRow, 1].Text = "'" + currentFormula;
sheet.Range[currentRow++, 2].Formula = currentFormula;
// Função MINUTE
currentFormula = "=MINUTE(0.78125)";
sheet.Range[currentRow, 1].Text = "'" + currentFormula;
sheet.Range[currentRow++, 2].Formula = currentFormula;
// Função MONTH
currentFormula = "=MONTH(9)";
sheet.Range[currentRow, 1].Text = "'" + currentFormula;
sheet.Range[currentRow++, 2].Formula = currentFormula;
// Função DAY
currentFormula = "=DAY(10)";
sheet.Range[currentRow, 1].Text = "'" + currentFormula;
sheet.Range[currentRow++, 2].Formula = currentFormula;
// Função TIME
currentFormula = "=TIME(4,5,7)";
sheet.Range[currentRow, 1].Text = "'" + currentFormula;
sheet.Range[currentRow++, 2].Formula = currentFormula;
// Função DATE
currentFormula = "=DATE(6,4,2)";
sheet.Range[currentRow, 1].Text = "'" + currentFormula;
sheet.Range[currentRow++, 2].Formula = currentFormula;
// Função RAND
currentFormula = "=RAND()";
sheet.Range[currentRow, 1].Text = "'" + currentFormula;
sheet.Range[currentRow++, 2].Formula = currentFormula;
// Função HOUR
currentFormula = "=HOUR(0.5)";
sheet.Range[currentRow, 1].Text = "'" + currentFormula;
sheet.Range[currentRow++, 2].Formula = currentFormula;
// Função MOD
currentFormula = "=MOD(5,3)";
sheet.Range[currentRow, 1].Text = "'" + currentFormula;
sheet.Range[currentRow++, 2].Formula = currentFormula;
// Função WEEKDAY
currentFormula = "=WEEKDAY(3)";
sheet.Range[currentRow, 1].Text = "'" + currentFormula;
sheet.Range[currentRow++, 2].Formula = currentFormula;
// Função YEAR
currentFormula = "=YEAR(23)";
sheet.Range[currentRow, 1].Text = "'" + currentFormula;
sheet.Range[currentRow++, 2].Formula = currentFormula;
// Função NOT
currentFormula = "=NOT(true)";
sheet.Range[currentRow, 1].Text = "'" + currentFormula;
sheet.Range[currentRow++, 2].Formula = currentFormula;
// Função OR
currentFormula = "=OR(true)";
sheet.Range[currentRow, 1].Text = "'" + currentFormula;
sheet.Range[currentRow++, 2].Formula = currentFormula;
// Função AND
currentFormula = "=AND(TRUE)";
sheet.Range[currentRow, 1].Text = "'" + currentFormula;
sheet.Range[currentRow++, 2].Formula = currentFormula;
// Função VALUE
currentFormula = "=VALUE(30)";
sheet.Range[currentRow, 1].Text = "'" + currentFormula;
sheet.Range[currentRow++, 2].Formula = currentFormula;
// Função LEN
currentFormula = "=LEN(\"world\")";
sheet.Range[currentRow, 1].Text = "'" + currentFormula;
sheet.Range[currentRow++, 2].Formula = currentFormula;
// Função MID
currentFormula = "=MID(\"world\",4,2)";
sheet.Range[currentRow, 1].Text = "'" + currentFormula;
sheet.Range[currentRow++, 2].Formula = currentFormula;
// Função ROUND
currentFormula = "=ROUND(7,3)";
sheet.Range[currentRow, 1].Text = "'" + currentFormula;
sheet.Range[currentRow++, 2].Formula = currentFormula;
// Função SIGN
currentFormula = "=SIGN(4)";
sheet.Range[currentRow, 1].Text = "'" + currentFormula;
sheet.Range[currentRow++, 2].Formula = currentFormula;
// Função INT
currentFormula = "=INT(200)";
sheet.Range[currentRow, 1].Text = "'" + currentFormula;
sheet.Range[currentRow++, 2].Formula = currentFormula;
// Função ABS
currentFormula = "=ABS(-1.21)";
sheet.Range[currentRow, 1].Text = "'" + currentFormula;
sheet.Range[currentRow++, 2].Formula = currentFormula;
// Função LN
currentFormula = "=LN(15)";
sheet.Range[currentRow, 1].Text = "'" + currentFormula;
sheet.Range[currentRow++, 2].Formula = currentFormula;
// Função EXP
currentFormula = "=EXP(20)";
sheet.Range[currentRow, 1].Text = "'" + currentFormula;
sheet.Range[currentRow++, 2].Formula = currentFormula;
// Função SQRT
currentFormula = "=SQRT(40)";
sheet.Range[currentRow, 1].Text = "'" + currentFormula;
sheet.Range[currentRow++, 2].Formula = currentFormula;
// Função PI
currentFormula = "=PI()";
sheet.Range[currentRow, 1].Text = "'" + currentFormula;
sheet.Range[currentRow++, 2].Formula = currentFormula;
// Função COS
currentFormula = "=COS(9)";
sheet.Range[currentRow, 1].Text = "'" + currentFormula;
sheet.Range[currentRow++, 2].Formula = currentFormula;
// Função SIN
currentFormula = "=SIN(45)";
sheet.Range[currentRow, 1].Text = "'" + currentFormula;
sheet.Range[currentRow++, 2].Formula = currentFormula;
// Função MAX
currentFormula = "=MAX(10,30)";
sheet.Range[currentRow, 1].Text = "'" + currentFormula;
sheet.Range[currentRow++, 2].Formula = currentFormula;
// Função MIN
currentFormula = "=MIN(5,7)";
sheet.Range[currentRow, 1].Text = "'" + currentFormula;
sheet.Range[currentRow++, 2].Formula = currentFormula;
// Função AVERAGE
currentFormula = "=AVERAGE(12,45)";
sheet.Range[currentRow, 1].Text = "'" + currentFormula;
sheet.Range[currentRow++, 2].Formula = currentFormula;
// Função SUM
currentFormula = "=SUM(18,29)";
sheet.Range[currentRow, 1].Text = "'" + currentFormula;
sheet.Range[currentRow++, 2].Formula = currentFormula;
// Função IF
currentFormula = "=IF(4,2,2)";
sheet.Range[currentRow, 1].Text = "'" + currentFormula;
sheet.Range[currentRow++, 2].Formula = currentFormula;
// Função SUBTOTAL
currentFormula = "=SUBTOTAL(3,Sheet1!A2:F2)";
sheet.Range[currentRow, 1].Text = "'" + currentFormula;
sheet.Range[currentRow++, 2].Formula = currentFormula;
// Definir a largura da primeira, segunda e terceira colunas
sheet.SetColumnWidth(1, 32);
sheet.SetColumnWidth(2, 16);
sheet.SetColumnWidth(3, 16);
// Criar um estilo de célula
CellStyle style = workbook.Styles.Add("Style");
// Definir o alinhamento horizontal à esquerda
style.HorizontalAlignment = HorizontalAlignType.Left;
// Aplicar o estilo à planilha
sheet.ApplyStyle(style);
// Salvar o arquivo resultante
workbook.SaveToFile("AddFormulasAndFunctions.xlsx", ExcelVersion.Version2016);
workbook.Dispose();
}
}
}
Como Ler Fórmulas e Funções no Excel com C# e VB.NET
Para ler fórmulas e funções em uma planilha do Excel, primeiro é necessário percorrer todas as células da planilha. Em seguida, utilize a propriedade Cell.HasFormula para localizar as células que contêm fórmulas ou funções e a propriedade CellRange.Formula para obter seu conteúdo.
As etapas detalhadas são as seguintes:
- Inicialize uma instância da classe Workbook.
- Carregue um arquivo Excel usando o método Workbook.LoadFromFile().
- Obtenha uma planilha específica pelo índice usando a propriedade Workbook.Worksheets[sheetIndex].
- Inicialize uma instância da classe StringBuilder.
- Acesse o intervalo utilizado da planilha usando a propriedade Worksheet.AllocatedRange.
- Percorra todas as células do intervalo utilizado.
- Localize as células que contêm fórmulas ou funções usando a propriedade Cell.HasFormula.
- Obtenha os nomes das células e suas fórmulas ou funções usando as propriedades CellRange.RangeAddressLocal e CellRange.Formula.
- Adicione os nomes das células e as fórmulas ou funções ao StringBuilder usando o método StringBuilder.AppendLine().
- Grave o conteúdo do StringBuilder em um arquivo .txt usando o método File.WriteAllText().
O código de exemplo completo é apresentado a seguir.
using Spire.Xls;
using System.IO;
using System.Text;
namespace ReadFormulasAndFunctions
{
internal class Program
{
static void Main(string[] args)
{
// Inicializa uma instância da classe Workbook
Workbook workbook = new Workbook();
// Carrega um arquivo Excel
workbook.LoadFromFile("AddFormulasAndFunctions.xlsx");
// Obtém a primeira planilha
Worksheet sheet = workbook.Worksheets[0];
// Inicializa uma instância da classe StringBuilder
StringBuilder sb = new StringBuilder();
// Acessa o intervalo utilizado da planilha
CellRange usedRange = sheet.AllocatedRange;
// Percorre todas as células do intervalo utilizado
foreach (CellRange cell in usedRange)
{
// Verifica se a célula atual contém uma fórmula ou função
if (cell.HasFormula)
{
// Obtém o nome da célula
string cellName = cell.RangeAddressLocal;
// Obtém a fórmula ou função
string formula = cell.Formula;
// Adiciona o nome da célula e a fórmula ou função ao StringBuilder
sb.AppendLine(cellName + " has a formula: " + formula);
}
}
// Grava o conteúdo do StringBuilder em um arquivo .txt
File.WriteAllText("ReadFormulasAndFunctions.txt", sb.ToString());
}
}
}
Conclusão
Neste artigo, apresentamos como ler fórmulas e funções em planilhas do Excel usando C# e VB.NET. Percorrendo todas as células do intervalo utilizado da planilha, é possível identificar aquelas que contêm fórmulas ou funções por meio da propriedade HasFormula e obter seu conteúdo com a propriedade Formula. Além disso, a classe StringBuilder permite organizar as informações recuperadas e exportá-las para um arquivo de texto, facilitando a consulta e o gerenciamento de fórmulas e funções em arquivos Excel.