Jump to content

Criar um ficheiro Excel a partir duma datagridvew e Adicionar linhas


gregurs

Recommended Posts

Boa noite tenho este código para gerar um ficheiro excel a partir duma datagrid que funciona na perfeição. O que eu quero fazer é inserir uma linha no excel para criar os titulos das colunas. Podem ajudar.

SaveFileDialog salvar = new SaveFileDialog();

Excel.Application App; // Aplicação Excel
Excel.Workbook WorkBook; // Pasta
Excel.Worksheet WorkSheet; // Planilha
object misValue = System.Reflection.Missing.Value;
App = new Excel.Application();
WorkBook = App.Workbooks.Add(misValue);
WorkSheet = (Excel.Worksheet)WorkBook.Worksheets.get_Item(1);
int i = 0;
int j = 0;

// passa as celulas do DataGridView para a Pasta do Excel
for (i = 0; i <= dataGridView1.RowCount - 1; i++)
{
 for (j = 0; j <= dataGridView1.ColumnCount - 1; j++)
 {
   DataGridViewCell cell = dataGridView1[j, i];
   WorkSheet.Cells[i + 1, j + 1] = cell.Value;
 }
}
// define algumas propriedades da caixa salvar
salvar.Title = "Exportar para Excel";
salvar.Filter = "Arquivo do Excel *.xls | *.xls";
salvar.ShowDialog(); // mostra
// salva o arquivo
WorkBook.SaveAs(salvar.FileName, Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue,
Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
WorkBook.Close(true, misValue, misValue);
App.Quit(); // encerra o excel
MessageBox.Show("Exportado com sucesso!");
Link to comment
Share on other sites

Esta é a linha onde os valores são afectados:

WorkSheet.Cells = cell.Value;

o que precisas fazer é escrever os títulos que queres da mesma forma.

E depois no for corrigires o valor do i e do j para não sobrepores o titulo.

Matraquilhos para Android.

Gratuito na Play Store.

https://play.google.com/store/apps/details?id=pt.bca.matraquilhos

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...

Important Information

By using this site you accept our Terms of Use and Privacy Policy. We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.