一個非常快的轉excel<br><br>unit Unit1;<br><br>interface<br><br>uses Classes,Forms,Windows,ExtCtrls,StdCtrls,SConnect,Controls,SysUtils,ComObj,DB,Dialogs;<br><br>Procedure ExportExcelFile(FileName: string; bWriteTitle: Boolean; aDataSet: TDataSet);stdcall;<br><br>var<br> arXlsBegin:array[0..5] of Word=($809, 8, 0, $10, 0, 0);<br> arXlsEnd:array[0..1] of Word = ($0A, 00);<br> arXlsString:array[0..5] of Word = ($204, 0, 0, 0, 0, 0);<br> arXlsNumber:array[0..4] of Word = ($203, 14, 0, 0, 0);<br> arXlsInteger:array[0..4] of Word = ($27E, 10, 0, 0, 0);<br> arXlsBlank:array[0..4] of Word = ($201, 6, 0, 0, $17);<br><br>implementation<br><br>Procedure ExportExcelFile(FileName: string; bWriteTitle: Boolean; aDataSet: TDataSet);<br>var<br> i:integer;<br> Col,row: word;<br> ABookMark: TBookMark;<br> aFileStream: TFileStream;<br>procedure incColRow;<br>begin<br><br> if Col = ADataSet.FieldCount - 1 then<br> begin<br> Inc(Row);<br> Col :=0;<br> end<br> else<br> Inc(Col);<br>end;<br><br>procedure WriteStringCell(AValue: string);<br>var<br> L: Word;<br>begin<br> L := Length(AValue);<br> arXlsString[1] := 8 + L;<br> arXlsString[2] := Row;<br> arXlsString[3] := Col;<br> arXlsString[5] := L;<br> aFileStream.WriteBuffer(arXlsString, SizeOf(arXlsString));<br> aFileStream.WriteBuffer(Pointer(AValue)^, L);<br> IncColRow;<br>end;<br><br>procedure WriteIntegerCell(AValue: integer);//<br>var<br> V: Integer;<br>begin<br> arXlsInteger[2] := Row;<br> arXlsInteger[3] := Col;<br> aFileStream.WriteBuffer(arXlsInteger, SizeOf(arXlsInteger));<br> V := (AValue shl 2) or 2;<br> aFileStream.WriteBuffer(V, 4);<br> IncColRow;<br>end;<br><br>procedure WriteFloatCell(AValue: double);<br>begin<br> arXlsNumber[2] := Row;<br> arXlsNumber[3] := Col;<br> aFileStream.WriteBuffer(arXlsNumber, SizeOf(arXlsNumber));<br> aFileStream.WriteBuffer(AValue, 8);<br> IncColRow;<br>end;<br><br>begin<br> if FileExists(FileName) then DeleteFile(FileName);<br> aFileStream := TFileStream.Create(FileName, fmCreate);<br> Try<br> aFileStream.WriteBuffer(arXlsBegin, SizeOf(arXlsBegin));<br> Col := 0; Row := 0;<br> if bWriteTitle then //寫Excel的Column<br> begin<br> for i := 0 to aDataSet.FieldCount - 1 do<br> WriteStringCell(aDataSet.Fields.FieldName); <br> end;<br> aDataSet.DisableControls;<br> ABookMark := aDataSet.GetBookmark;<br> aDataSet.First;<br> while not aDataSet.Eof do<br> begin<br> for i := 0 to aDataSet.FieldCount - 1 do<br> case ADataSet.Fields.DataType of<br> ftSmallint, ftInteger, ftWord, ftAutoInc, ftBytes:<br> WriteIntegerCell(aDataSet.Fields.AsInteger);<br> ftFloat, ftCurrency, ftBCD:<br> WriteFloatCell(aDataSet.Fields.AsFloat)<br> else<br> WriteStringCell(aDataSet.Fields.AsString);<br> end;<br> aDataSet.Next;<br> end;<br><br> AFileStream.WriteBuffer(arXlsEnd, SizeOf(arXlsEnd));<br> if ADataSet.BookmarkValid(ABookMark) then<br> aDataSet.GotoBookmark(ABookMark);<br> Finally<br> ADataSet.EnableControls;<br> end;<br>end;<br><br>end.