using System.ComponentModel;
using System.Windows.Forms;
using Excel = Microsoft.Office.Interop.Excel;
using System.Collections.Generic;
using System.Runtime.InteropServices;
namespace AutomacaoExcel.Forms.Credenciador
public partial class Credenciador : Form
ProcessamentoCredenciador ClasseProcessamento = new ProcessamentoCredenciador();
string ArquivoCredenciador;
string ArquivoFuncionalidades;
Excel.Application ExcelApp = null;
Excel.Workbook ExcelMatriz = null;
Excel.Workbook ExcelDeclaracaoEscopo = null;
Excel.Workbook ExcelFuncionalidades = null;
private void Form1_Load(object sender, EventArgs e)
textBox1.Text = @"C:\Users\nakao\OneDrive\Documentos\UL\INPUT\INPUT Credenciador Real\Certificação_Credenciador_Release-22.1_v1.0.xlsx";
textBox2.Text = @"C:\Users\nakao\OneDrive\Documentos\UL\INPUT\INPUT Credenciador Real\Declaração de Escopo do Parceiro_v1.0.xlsx";
textBox3.Text = @"C:\Users\nakao\OneDrive\Documentos\UL\INPUT\INPUT Credenciador Real\Controle de Funcionalidades 08122021.xlsx";
textBox4.Text = @"C:\Users\nakao\OneDrive\Documentos\UL\OUTPUT\REAL";
backgroundWorker.WorkerReportsProgress = true;
private void processar_Click(object sender, EventArgs e)
ArquivoCredenciador = textBox1.Text;
ArquivoEscopo = textBox2.Text;
ArquivoFuncionalidades = textBox3.Text;
DiretorioSaida = textBox4.Text;
DiretorioSaida += @"\Credenciadores\";
const string message = "Iniciar processamento?";
const string caption = "Processamento Credenciadores";
var result = MessageBox.Show(message, caption, MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
if (result == DialogResult.OK)
ExcelApp = new Excel.Application();
ExcelApp.Visible = false;
ExcelDeclaracaoEscopo = ExcelApp.Workbooks.Open(ArquivoEscopo);
ProcessamentoCredenciador.CriarArquivosCredenciador(ExcelApp, ExcelDeclaracaoEscopo, ArquivoCredenciador, ArquivoEscopo, DiretorioSaida);
DirectoryInfo d = new DirectoryInfo(DiretorioSaida);
Files = d.GetFiles("*.xlsx");
this.progressBar1.Maximum = Files.Length;
backgroundWorker.RunWorkerAsync();
exx += "===========================================";
exx += "\nOcorreu um erro durante o processamento.\nVeja os detalhes abaixo:";
exx += String.Format("\nERRO: {0}", err.Message);
exx += String.Format("\nERRO: {0}", err.StackTrace);
exx += "\n===========================================";
private void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
BackgroundWorker worker = sender as BackgroundWorker;
ExcelFuncionalidades = ExcelApp.Workbooks.Open(ArquivoFuncionalidades);
List<ProcessamentoCredenciador.DestalhesFuncionalidade> lstFuncionalidades = ProcessamentoCredenciador.ListarFuncionalidades(ExcelFuncionalidades);
foreach (FileInfo file in Files)
worker.ReportProgress(count++);
ExcelMatriz = ExcelApp.Workbooks.Open(file.FullName);
foreach (Excel.Worksheet ExcelMatriz_sheet in ExcelMatriz.Sheets)
int rows = ExcelMatriz_sheet.UsedRange.Rows.Count;
KeyValuePair<int, int> index = ProcessamentoCredenciador.EncontrarColunaFuncionalidade(ExcelMatriz_sheet);
for (int row = (index.Key + 1); rowCycle <= rows; row++)
string strBoletim = ExcelMatriz_sheet.Cells[row, 2].Value2;
string strCliente = file.Name.Replace(file.Extension, "").Split('-')[0].Trim();
string strFuncionalidade = ExcelMatriz_sheet.Cells[row, index.Value].Value2;
if (!String.IsNullOrEmpty(strBoletim) && !strBoletim.ToUpper().Equals("BOLETIM"))
bool boolBoletimEcontrado = ProcessamentoCredenciador.BuscarBoletinsHabilitados(ExcelDeclaracaoEscopo, strCliente, strBoletim);
if (!boolBoletimEcontrado)
Excel.Range cells = (Excel.Range)ExcelMatriz_sheet.Range[String.Format("B{0}", row), Type.Missing];
Excel.Range del = cells.EntireRow;
bool boolFuncEcontrado = ProcessamentoCredenciador.BuscarFuncionalidades(lstFuncionalidades, strCliente, strFuncionalidade);
Excel.Range cells = (Excel.Range)ExcelMatriz_sheet.Range[String.Format("B{0}", row), Type.Missing];
Excel.Range del = cells.EntireRow;
Marshal.ReleaseComObject(ExcelMatriz);
MessageBox.Show("Processamento finalizado com sucesso!");
exx += "===========================================";
exx += "\nOcorreu um erro durante o processamento.\nVeja os detalhes abaixo:";
exx += String.Format("\n\nERRO: {0}", err.Message);
exx += String.Format("\n\nERRO: {0}", err.StackTrace);
exx += "\n===========================================";
if (ExcelDeclaracaoEscopo != null)
Marshal.ReleaseComObject(ExcelDeclaracaoEscopo);
ExcelDeclaracaoEscopo = null;
if (ExcelFuncionalidades != null)
Marshal.ReleaseComObject(ExcelFuncionalidades);
ExcelFuncionalidades = null;
Marshal.ReleaseComObject(ExcelApp);
private void backgroundWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
progressBar1.Value = e.ProgressPercentage;
private void backgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
private void cancelar_Click(object sender, EventArgs e)
private void button3_Click(object sender, EventArgs e)
DialogResult result = openFileDialog1.ShowDialog();
if (result == DialogResult.OK)
textBox1.Text = openFileDialog1.FileName;
private void button4_Click(object sender, EventArgs e)
DialogResult result = openFileDialog1.ShowDialog();
if (result == DialogResult.OK)
textBox2.Text = openFileDialog1.FileName;
private void button5_Click(object sender, EventArgs e)
DialogResult result = openFileDialog1.ShowDialog();
if (result == DialogResult.OK)
textBox3.Text = openFileDialog1.FileName;
private void button6_Click(object sender, EventArgs e)
DialogResult result = folderBrowserDialog1.ShowDialog();
if (result == DialogResult.OK)
textBox4.Text = folderBrowserDialog1.SelectedPath;
private bool ValidarCampos()
if (String.IsNullOrEmpty(textBox1.Text))
MessageBox.Show("Selecione a Matriz do Credenciador");
else if (!File.Exists(textBox1.Text))
MessageBox.Show("Arquivo não encontrado");
if (String.IsNullOrEmpty(textBox2.Text))
MessageBox.Show("Selecione o arquivo Declaração do Escopo");
else if (!File.Exists(textBox2.Text))
MessageBox.Show("Arquivo não encontrado");
if (String.IsNullOrEmpty(textBox3.Text))
MessageBox.Show("Selecione o arquivo Controle de Funcionalidades");
else if (!File.Exists(textBox3.Text))
MessageBox.Show("Arquivo não encontrado");
if (String.IsNullOrEmpty(textBox4.Text))
MessageBox.Show("Selecione um diretório para gerar os arquivos de saída");
else if (!Directory.Exists(textBox4.Text))
MessageBox.Show("Diretório inválido");
private void HabilitarCampos(bool habilitar)
textBox1.Enabled = habilitar;
textBox2.Enabled = habilitar;
textBox3.Enabled = habilitar;
textBox4.Enabled = habilitar;
button3.Enabled = habilitar;
button4.Enabled = habilitar;
button5.Enabled = habilitar;
button6.Enabled = habilitar;
processar.Enabled = habilitar;
cancelar.Enabled = habilitar;