Example returning TExcelFile from a DataSnap serve

Hello, using XE7 here and wanted to build an excel sheet in memory and return it to a web app from a datasnap server as an ExcelFile.  Do you have any examples that do this?


Thanks

Hi,

I am no expert in DataSnap Server, but I think you would have to serialize the ExcelFile to a stream.

For example, you could define a method in the server:

function TServerMethods1.GetExcelFile(Xlsx: boolean): TStream;
var
  xls: TExcelFile;
  FileFormat: TFileFormats;
begin
  Result := TMemoryStream.Create;
  xls:= TXlsFile.Create(1, true);
  try
    xls.SetCellValue(1, 1, 'Hi from FlexCel');

    if Xlsx then FileFormat := TFileFormats.Xlsx else FileFormat := TFileFormats.Xls;
    xls.Save(Result, FileFormat);
    Result.Position := 0;
  finally
    xls.Free;
  end;
end;

And from the client:
procedure TForm5.Button1Click(Sender: TObject);
var
  Server: TServerMethods1Client;
  ms: TStream;
  fs: TFileStream;
begin
  Server := TServerMethods1Client.Create(SQLConnection1.DBXConnection);
  try
    ms := Server.GetExcelFile(true);
    fs := TFileStream.Create('r:\test.xlsx', fmCreate);
    try
      fs.CopyFrom(ms, ms.Size);
    finally
      fs.Free;
    end;
  finally
    Server.Free;
  end;
end;

This would save the xls/x file to a file in the client. You could of course create another TXlsFile in the client and open the stream with it, to keep manipulating the file. But it all depends on what you want to do with the file in the client. Also you mention that the client is webpage, but I don't know if it is using webbroker or just javascript. But whatever it uses, the code should be similar.

Thanks for the sample code.   I will try to adapt it to be usable from a web browser,  my main issue is changing the content type on the response to xls.  The data snap documentation is pathetic.