Dataset存成CSV檔
use Excel2000;
procedure TFMstGDS_1903R14.SaveToExcel_CSV(var DBGrid: TInfoDBGrid);
var aExeclFile:TSaveDialog;
begin
if DBGrid.DataSource=nil then Exit;
if not DBGrid.DataSource.DataSet.Active then Exit;
if DBGrid.DataSource.DataSet.RecordCount = 0 then Exit;
aExeclFile:=TSaveDialog.Create(nil);
try
aExeclFile.DefaultExt:='.CSV';
aExeclFile.Filter:='*.CSV|*.CSV';
aExeclFile.Title:='請選擇EXECL(CSV)的目錄';
aExeclFile.Options:=[ofOverwritePrompt,ofHideReadOnly,ofEnableSizing];
if aExeclFile.Execute then DBGrid3Excel_CSV(DBGrid,aExeclFile.filename);
finally
aExeclFile.Free;
end;
end;
procedure TFMstGDS_1903R14.DBGrid3Excel_CSV(var DBGrid: TINFODBGrid;
ExcelFileName: string);
var
lcid: integer;
Temp_Worksheet: _WorkSheet;
SheetType:OleVariant;
ExCelApplication1 : TExCelApplication;
ExcelWorkBook1 : TExcelWorkBook;
ExcelWorksheet1 : TExcelWorksheet;
ExcelChart1 : TExcelChart;
begin
inherited;
SaveDataSet(DBGrid.DataSource.DataSet,ExcelFileName, ',');
try
//開始轉換
lcid := GetUserDefaultLCID;
//動態新增;
ExCelApplication1 := TExCelApplication.Create(nil);
ExcelWorkBook1 := TExcelWorkBook.Create(nil);
ExcelWorksheet1 := TExcelWorksheet.Create(nil);
ExcelChart1 := TExcelChart.Create(nil);
//開啟現存的檔案
ExcelApplication1.Connect;
ExcelWorkbook1.ConnectTo(
ExcelApplication1.Workbooks.Open (ExcelFileName, EmptyParam,EmptyParam,EmptyParam,EmptyParam,
EmptyParam,EmptyParam,EmptyParam,EmptyParam, EmptyParam,EmptyParam,EmptyParam,EmptyParam,0));
ExcelWorksheet1.ConnectTo(ExcelWorkbook1.Worksheets[1] as _Worksheet);
ExcelWorksheet1.Name := '資料';
except
ON E: EXCEPTION DO
BEGIN
showmessage(e.Message);
showmessage('無法連上Excel');
END;
end;
end;
procedure TFMstGDS_1903R14.SaveDataSet(TT: TDataSet; FileName,
Delimiter: String);
var
i, j : integer;line : string;
M : TStringList;
begin
TT.Active := true;
TT.First;
M := TStringList.Create;
//M.Add(Printstr); //條件
{//抬頭
Line := TT.Fields[0].DisplayName;
For i := 1 to TT.FieldCount -1 do
begin
if TT.Fields[i].Visible then
Line := Line + Delimiter + TT.Fields[i].DisplayLabel;
end;
M.Add(Line);
}
j:=0;
while not TT.Eof do
begin
Line := TT.Fields[0].AsString;
For i := 1 to TT.FieldCount -1 do
begin
if TT.Fields[i].Visible then
begin
if TT.Fields[i].DataType = ftString then
begin
if Copy(TT.Fields[i].AsString, 1, 1) = '0' then Line := Line + Delimiter +''''+ TT.Fields[i].AsString
else Line := Line + Delimiter + TT.Fields[i].AsString;
end
else
begin
Line := Line + Delimiter + TT.Fields[i].AsString;
end;
end;
end;
M.Add(Line);
inc(j);
// Label1.Caption := '第' + inttostr(j) + '筆';
Application.ProcessMessages;
TT.Next;
end;
M.SaveToFile(FileName);
end;
沒有留言:
張貼留言