Este truco sirve como ampliación al de Neftalí en el de [HTML]<a href=http://www.clubdelphi.com/trucos/index.php?id=38 >Exportar un StringGrid a un Fichero</a>
[/HTML]
Hay que añadir al uses el Excel_TLB, ActiveX.
Y a la función sólo le pasamos el stringgrid que queremos exportar y el rango de columnas y filas que queremos exportar
Código Delphi
[-]
procedure ExportaExcel(pStringGrid : TstringGrid; c0,r0,c1,r1 : Integer);
var ExLin, ExCol, i, Linea, AuxInteger : Integer;
AuxFloat : Double;
AuxFecha : tDatetime;
c : TCursor;
Excel, ExcelDoc, WS : Variant;
begin
c := Screen.Cursor;
Screen.Cursor := crHourGlass;
with pStringGrid do begin
try
coinitialize(nil);
Excel := CreateOleObject('Excel.Application');
ExcelDoc := Excel.Workbooks.Add;
WS := ExcelDoc.ActiveSheet;
Excel.Visible := true;
ExCol := 0;
for i := c0 to c1 do begin
inc(ExCol);
ws.Cells.Item[1, ExCol]:= cells[i, 0];
end;
for linea := r0 to r1 do begin
inc(ExLin);
ExCol := 0;
for i := c0 to c1 do begin
inc(ExCol);
try
try
if pos('/', cells[i, linea - 1]) <> 0 then begin
AuxFecha := strtodatetime(cells[i, linea - 1]));
ws.Cells.Item[ExLin, ExCol] := AuxFecha;
end
else AuxFecha := strtodatetime('GENERA EXCEPCION');
except
try
AuxInteger := strtoint(cells[i,linea-1]));
ws.Cells.Item[ExLin,ExCol]:= AuxInteger;
except
try
AuxFloat := strtofloat(cells[i,linea-1]);
ws.Cells.Item[ExLin,ExCol]:= AuxFloat;
except
ws.Cells.Item[ExLin,ExCol]:= cells[i,linea-1];
end;
end;
end;
except end;
end;
end;
ws.cells.entirecolumn.autofit;
finally
screen.Cursor := c;
end;
end;
end;
Un ejemplo de uso puede ser:
Código Delphi
[-]
ExportaExcel(StringGrid1, 0, StringGrid1.ColCount-1, 0, StringGrid.RowCount-1);
Editado: hay que añadir tambien la uses ActiveX, y la funcion AllTrim la he quitado.