Exportar un StringGrid a Excel

3809 vistas

Aquà tenemos un procedure que nos permite exportar el contenido de un TStringGrid a Excel



delphi
  1. procedure XlsWriteCellLabel(XlsStream: TStream; const ACol, ARow: Word;
  2.   const AValue: string);
  3. var
  4.   L: Word;
  5. const
  6.   {$J+}
  7.   CXlsLabel: array[0..5] of Word = ($204, 0, 0, 0, 0, 0);
  8.   {$J-}
  9. begin
  10.   L := Length(AValue);
  11.   CXlsLabel[1] := 8 + L;
  12.   CXlsLabel[2] := ARow;
  13.   CXlsLabel[3] := ACol;
  14.   CXlsLabel[5] := L;
  15.   XlsStream.WriteBuffer(CXlsLabel, SizeOf(CXlsLabel));
  16.   XlsStream.WriteBuffer(Pointer(AValue)^, L);
  17. end;
  18.  
  19.  
  20. function SaveAsExcelFile(AGrid: TStringGrid; AFileName: string): Boolean;
  21. const
  22.   {$J+} CXlsBof: array[0..5] of Word = ($809, 8, 00, $10, 0, 0); {$J-}
  23.   CXlsEof: array[0..1] of Word = ($0A, 00);
  24. var
  25.   FStream: TFileStream;
  26.   I, J: Integer;
  27. begin
  28.   FStream := TFileStream.Create(PChar(AFileName), fmCreate or fmOpenWrite);
  29.   try
  30.     CXlsBof[4] := 0;
  31.     FStream.WriteBuffer(CXlsBof, SizeOf(CXlsBof));
  32.     for i := 0 to AGrid.ColCount - 1 do
  33.       for j := 0 to AGrid.RowCount - 1 do
  34.         XlsWriteCellLabel(FStream, I, J, AGrid.cells[i, j]);
  35.     FStream.WriteBuffer(CXlsEof, SizeOf(CXlsEof));
  36.     Result := True;
  37.   finally
  38.     FStream.Free;
  39.   end;
  40. end;



Recordemos que la directiva $J controla si una constante puede ser modificada o no. Para más información, consultar la ayuda de Delphi de esta directiva.

Un posible modo de uso serÃa:



delphi
  1. SaveAsExcelFile(StringGrid1,'c:\testxls.xls');