function TForm1.ExportToExcel(strConnectionString,strSQL: string): Boolean;
var
xlApp,xlBook,xlSheet,xlQuery: Variant;
adoConnection,adoRecordset: Variant;
begin
adoConnection := CreateOleObject('ADODB.Connection');
adoRecordset := CreateOleObject('ADODB.Recordset');
adoConnection.Open(strConnectionString);
adoRecordset.CursorLocation := adUseClient;
adoRecordset.Open(strSQL,adoConnection,1,3);
xlApp := CreateOleObject('Excel.Application');
xlBook := xlApp.Workbooks.Add;
xlSheet := xlBook.Worksheets['sheet1'];
xlApp.Visible := True;
{把数据集导入EXCEL数据} xlQuery := xlSheet.QueryTables.Add(adoRecordset,xlSheet.Range['A1']);
{关键是以上这一句}
xlQuery.FieldNames := True;
xlQuery.RowNumbers := False;
xlQuery.FillAdjacentFormulas := False;
xlQuery.PreserveFormatting := True;
xlQuery.RefreshOnFileOpen := False;
xlQuery.BackgroundQuery := True;
//xlQuery.RefreshStyle := xlInsertDeleteCells;
xlQuery.SavePassword := True;
xlQuery.SaveData := True;
xlQuery.AdjustColumnWidth := True;
xlQuery.RefreshPeriod := 0;
xlQuery.PreserveColumnInfo := True;
xlQuery.FieldNames := True;
xlQuery.Refresh;
end;
var
xlApp,xlBook,xlSheet,xlQuery: Variant;
adoConnection,adoRecordset: Variant;
begin
adoConnection := CreateOleObject('ADODB.Connection');
adoRecordset := CreateOleObject('ADODB.Recordset');
adoConnection.Open(strConnectionString);
adoRecordset.CursorLocation := adUseClient;
adoRecordset.Open(strSQL,adoConnection,1,3);
xlApp := CreateOleObject('Excel.Application');
xlBook := xlApp.Workbooks.Add;
xlSheet := xlBook.Worksheets['sheet1'];
xlApp.Visible := True;
{把数据集导入EXCEL数据} xlQuery := xlSheet.QueryTables.Add(adoRecordset,xlSheet.Range['A1']);
{关键是以上这一句}
xlQuery.FieldNames := True;
xlQuery.RowNumbers := False;
xlQuery.FillAdjacentFormulas := False;
xlQuery.PreserveFormatting := True;
xlQuery.RefreshOnFileOpen := False;
xlQuery.BackgroundQuery := True;
//xlQuery.RefreshStyle := xlInsertDeleteCells;
xlQuery.SavePassword := True;
xlQuery.SaveData := True;
xlQuery.AdjustColumnWidth := True;
xlQuery.RefreshPeriod := 0;
xlQuery.PreserveColumnInfo := True;
xlQuery.FieldNames := True;
xlQuery.Refresh;
end;
xlApp := Unassigned;
xlBook := Unassigned;
xlSheet := Unassigned;
xlQuery := Unassigned;
把 xlQuery.FieldNames := True;
改为 xlQuery.FieldNames := false;