procedure pr_DataSetToExcel(ADataset: TDataset);
var
ExcelApp, sheet, range: Variant;
i, Col, Row, iWidth: Integer;
bmMark:TBookmark;
strFormat:OleVariant; //必須宣告OleVariant的資料型態, 傳入NumberFormatLocal
begin
ExcelApp := CreateOleObject('Excel.Application');
ExcelApp.Visible := false;
ExcelApp.DisplayAlerts := false; //
ExcelApp.WorkBooks.Add();
ExcelApp.WorkSheets[1].Activate;
sheet := ExcelApp.WorkSheets[1].Activate;
ExcelApp.ActiveWorkBook.Saved := false;
strFormat:='@'; //將儲存格改成文字格式
bmMark := ADataset.GetBookmark;
ADataset.DisableControls;
Try
//欄位
ADataset.First();
Row := 1;
ExcelApp.ActiveSheet.Rows[Row].NumberFormatLocal:=strFormat; //將儲存格改成文字格式
for i := 0 to ADataset.FieldCount - 1 do
begin
Col := i + 1;
ExcelApp.Cells[Row, Col].Value := ADataset.Fields[i].DisplayLabel;
ExcelApp.Cells[Row, Col].Font.FontStyle := 2;
iWidth :=
Max(ExcelApp.Cells[Row, Col].ColumnWidth,
Length(ExcelApp.Cells[Row, Col].Value)+1);
ExcelApp.Cells[Row, Col].ColumnWidth := iWidth;
end;
//資料
Row := 2;
while not ADataset.Eof do
begin
ExcelApp.ActiveSheet.Rows[Row].NumberFormatLocal:=strFormat;//將儲存格改成文字格式
for i := 0 to ADataset.FieldCount - 1 do
begin
Col := i + 1;
ExcelApp.Cells[Row, Col].Value := Trim(ADataset.Fields[i].AsString);
iWidth :=
Max(ExcelApp.Cells[Row, Col].ColumnWidth,
Length(ExcelApp.Cells[Row, Col].Value)+1);
ExcelApp.Cells[Row, Col].ColumnWidth := iWidth;
end;
ADataset.Next();
Row := Row + 1;
end;
Finally
ADataset.GotoBookmark(bmMark);
ADataset.EnableControls;
End;
//ExcelApp.ActiveSheet.Columns[1].ColumnWidth := 5;
ExcelApp.Visible := True;
//ExcelApp.WorkBooks[1].SaveAs(xlsPath);
//ExcelApp.WorkBooks[1].Close();
//Obj_Query.First();
//ExcelApp.Quit;
end;
沒有留言:
張貼留言