Created
January 14, 2016 18:30
-
-
Save luan122/420d034594c180d99a0f to your computer and use it in GitHub Desktop.
Exemplo pratico para exportar dados de uma datagridview para um arquivo .xls em C#
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
internal bool exportaExcel2(DataGridView dGv, string filename) | |
{ | |
bool retorno = false; | |
// Cria o Excel. | |
Excel.Application Ex = new Excel.Application(); | |
Excel.Workbook Wb = Ex.Workbooks.Add(Type.Missing); | |
Excel.Worksheet Ws = null; | |
//Este DataTable está aqui para absorver os dados do DataGrid e ser tratado dentro do Excel | |
DataTable dt = new DataTable(); | |
//Lista usada para gerar as colunas | |
List<String> nomesH = new List<String>(); | |
// Valor nulo para ser usado como parametro dentro de funções do Excel | |
object misValue = System.Reflection.Missing.Value; | |
try | |
{ | |
for (int j = 0; j < dGv.Columns.Count; j++) | |
{ | |
dt.Columns.Add(Convert.ToString(dGv.Columns[j].HeaderText)); | |
nomesH.Add(Convert.ToString(dGv.Columns[j].HeaderText)); | |
} | |
DataRow drTemp = null; | |
foreach (DataGridViewRow dr in dGv.Rows) | |
{ | |
drTemp = dt.NewRow(); | |
for (int a = 0; a < nomesH.Count; a++) | |
{ | |
drTemp[nomesH[a]] = dr.Cells[nomesH[a]].Value; | |
} | |
dt.Rows.Add(drTemp); | |
} | |
int colunas = 0; | |
int linhas = 0; | |
// Copia o DataTable dentro de uma Array do tipo Objeto | |
object[,] dadosBrutos = new object[dt.Rows.Count + 1, dt.Columns.Count]; | |
// Copia o cabeçalho na primeira linha do Array | |
for (colunas = 0; colunas <= dt.Columns.Count - 1; colunas++) | |
{ | |
dadosBrutos[0, colunas] = dt.Columns[colunas].ColumnName; | |
} | |
// Copia os dados de cada coluna dentro do Array | |
for (colunas = 0; colunas <= dGv.Columns.Count - 1; colunas++) | |
{ | |
for (linhas = 0; linhas <= dGv.Rows.Count - 1; linhas++) | |
{ | |
dadosBrutos[linhas + 1, colunas] = dt.Rows[linhas].ItemArray[colunas]; | |
} | |
} | |
// Calcula a ultima letra da planilha | |
string finalLetraCol = ExcelNomeColuna(dt.Columns.Count); | |
//Inicia a planilha | |
Ws = Wb.ActiveSheet; | |
//Da nome a planilha | |
Ws.Name = "Planilha 1"; | |
//Define a série a ser adicionada na planilha (Esse método é mais rápido doque escrever celular por celula) | |
string serieDeDados = string.Format("A1:{0}{1}", finalLetraCol, dt.Rows.Count + 1); | |
//Insere os dados dentro da planilha | |
Ws.Range[serieDeDados, Type.Missing].Value2 = dadosBrutos; | |
//Previne que o Programa pergunte se quer substituir novamente. | |
Ex.DisplayAlerts = false; | |
//Salva a planilha | |
Wb.SaveAs(filename, Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, Excel.XlSaveAsAccessMode.xlNoChange, misValue, misValue, misValue, misValue, misValue); | |
//Retorna positivo, para o programa saber que tudo ocorreu bem | |
retorno = true; | |
} | |
catch (Exception ex) | |
{ | |
MessageBox.Show(ex.Message); | |
return retorno; | |
} | |
finally | |
{ | |
try | |
{ | |
//Fecha a area de trabalho do Excel | |
Wb.Close(true, Type.Missing, Type.Missing); | |
//Limpa a area de trabalho do Excel | |
Wb = null; | |
// Limpa e fecha a planilha | |
Ex.Quit(); | |
int abc = 0; | |
//Garantindo que o Excel será fechado | |
while (Ex.Quitting) | |
{ | |
Application.DoEvents(); | |
} | |
Ex = null; | |
Ws = null; | |
Ex = null; | |
Wb = null; | |
// Coleta as sobras de memória | |
GC.Collect(); | |
GC.WaitForPendingFinalizers(); | |
} | |
catch (Exception) | |
{ | |
throw; | |
} | |
} | |
return retorno; | |
} | |
public string ExcelNomeColuna(int Col) | |
{ | |
string functionReturnValue = null; | |
if (Col < 0 & Col > 256) | |
{ | |
MessageBox.Show("Argumento invalido"); | |
return functionReturnValue; | |
} | |
Int16 i = default(Int16); | |
Int16 r = default(Int16); | |
string S = null; | |
if (Col <= 26) | |
{ | |
S = Convert.ToString((char)(Col + 64)); | |
} | |
else | |
{ | |
r = (short)((float)(Col % 26)); | |
i = (short)Math.Floor((float)(Col / 26)); | |
if (r == 0) | |
{ | |
r = 26; | |
i = (short)(i - 1); | |
} | |
S = Convert.ToString((char)(i + 64)) + Convert.ToString((char)(r + 64)); | |
} | |
functionReturnValue = S; | |
return functionReturnValue; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment