Volevo sapere se qualcuno è un modo in cui posso esportare i dati da un DBGrid in Excel? Sto usando Delphi 7, Excel 2007 e ADO.
Qualsiasi aiuto sarà apprezzato.Esportare dati da un DBGrid a Excel
risposta
Se si desidera una rapida esportazione dei dati grezzi, basta esportare il set di record (ADODataset.recordset) con qualcosa di simile:
procedure ExportRecordsetToMSExcel(DestName: string; Data: _Recordset);
var
ovExcelApp: OleVariant;
ovExcelWorkbook: OleVariant;
ovWS: OleVariant;
ovRange: OleVariant;
begin
ovExcelApp := CreateOleObject('Excel.Application'); //If Excel isnt installed will raise an exception
try
ovExcelWorkbook := ovExcelApp.WorkBooks.Add;
ovWS := ovExcelWorkbook.Worksheets.Item[1]; // go to first worksheet
ovWS.Activate;
ovWS.Select;
ovRange := ovWS.Range['A1', 'A1']; //go to first cell
ovRange.Resize[Data.RecordCount, Data.Fields.Count];
ovRange.CopyFromRecordset(Data, Data.RecordCount, Data.Fields.Count); //this copy the entire recordset to the selected range in excel
ovWS.SaveAs(DestName, 1, '', '', False, False);
finally
ovExcelWorkbook.Close(SaveChanges := False);
ovWS := Unassigned;
ovExcelWorkbook := Unassigned;
ovExcelApp := Unassigned;
end;
end;
E se vogliamo esportare un ClientDataset in Excel, allora cosa facciamo? – Amin
Se non si dispone di un recordset, è necessario iterare il set di dati e scrivere celle di accesso Excel. ad esempio: ovWS.Cells [RowIndex, ColumnIndex] .Value: = Dataset.FieldByName ('foo'). AsString; –
Non esportare la DBGrid, esportare il set di dati http://stackoverflow.com/a/16642049/1699210 basta compilare arrData dell'esempio fornito con i valori del campo. – bummi
Anche io avrei dato il riferimento che Bummi ha dato. Per utilizzare l'approccio per array varianti, devi sapere quante righe hai nella query. Altrimenti potrebbe essere più semplice usare l'approccio csv che ho dato in quella domanda. –
@ No'amNewman a seconda dei datatay, l'approccio csv potrebbe dare più problemi nelle conversioni, ad es. DateTime values ... – bummi