I am trying to export DevExpress TdxDBGrid into XLSX format (yes, there are still Delphi 6 programs that uses TdxDBGrid!) but my program can have more general application as well.
So, TdxDBGrid has to export to XLS file out of the box. This is implemented by having Stream: TFileStream
object:
procedure TdxDBGridExport.Execute;
begin
Stream := TFileStream.Create(FileName, fmCreate);
try
SaveToStream(Stream);
finally
Stream.Free;
Stream := nil;
end;
end;
into which the exporter code write all the necessary binary information, e.g., writing of the column headers contains this code:
for i := 0 to GroupColumnCount - 1 do
begin
XLSBlank[2] := TotalCount;
XLSBlank[3] := i;
Stream.WriteBuffer(XLSBlank, SizeOf(XLSBlank));
end;
So - finally, the entire Excel file exists in the Stream
object in the binary format. And the saving the Stream
into file creates a XLS file.
I tried to complete my task by reading this XLS file in the in-memory ActiveX Excel application object and then saving it as a XLSX file, e.g. using the code:
var ExcelApp: ExcelApplication;
Workbook: ExcelWorkbook;
begin
ExcelApp := CoExcelApplication.Create;
try
ExcelApp.Visible[LOCALE_USER_DEFAULT] := False;
ExcelApp.DisplayAlerts[LOCALE_USER_DEFAULT] := False;
// Open the xls file
Workbook := ExcelApp.Workbooks.Open(AFileName, EmptyParam,
EmptyParam, EmptyParam, EmptyParam, EmptyParam, EmptyParam, EmptyParam,
EmptyParam, EmptyParam, EmptyParam,
//EmptyParam, EmptyParam,
EmptyParam,
EmptyParam, LOCALE_USER_DEFAULT);
try
// Save as xlsx
Workbook.SaveAs(ANewFileName,
51, //xlOpenXMLWorkbook,
EmptyParam,
EmptyParam, EmptyParam, EmptyParam, xlNoChange, EmptyParam, EmptyParam,
//EmptyParam,
EmptyParam, EmptyParam, LOCALE_USER_DEFAULT);
DeleteFile(AFileName);
Result:=True;
finally
Workbook := nil;
end;
finally
ExcelApp.Quit;
ExcelApp := nil;
end;
end;
This code is fully functional, and it even works on the older Windows versions, but the recent Windows versions issues error message:
You are attempting to open a file type that is blocked by your File Block settings in the Trust Center.
When my Excel application object tries to load XLS file. Trust Center configuration settings allows 'Open selected file types in Protected View and allow editing' as the maximal freedom. So - I can allow opening file in the Protected View, but this Protected View (in the nonvisual regime) give this error message. Trust Center does not provide the option to make further exemptions.
So - practically, my solution via loading XLS and saving as XLSX does not work.
I now have an idea, that maybe I can load Stream: TFileStream
directly into ActiveX Excel (Delphi in memory application object) and then I can immediately save it as XLSX file avoiding the saving and opening XLS file. Is such in-memory loading of ActiveX Excel Delphi application object possible and how to do it?