PDA

Ver la Versión Completa : Exportar un StringGrid a un fichero


Neftali [Germán.Estévez]
08-06-2006, 13:22:10
Éste truco ha llegado por la necesidad de exportar el contenido de un StringGrid hacia un fichero con las columnas separadas por TABs.
Definimos una constante CHAR_SEP como separador; Modificando ésta constante podemos usar TAB, ; , Saltos de linea,...

El código:


const
CHAR_SEP = ';';
// CHAR_SEP = #9;
// CHAR_SEP = '--';
//... diferentes posibilidades
//... different possibilities
var
i, j:Integer;
Str:String;
TS:TStrings;
begin

// Inicializamos
// initialize
Str := '';
// Para cada línea de las selecciondas
// for selected lines
for i := (StringGrid1.Selection.Top) to (StringGrid1.Selection.Bottom) do
begin
// Si no es la 1ª linea, añadimos un salto de línea
// if not is the first line tou must add a carry return
if (i <> StringGrid1.Selection.Top) then begin
Str := Str + #13#10;
end;
// Para cada elemento dentro de la línea (celdas)...
// for the elements of the line...
for j := 0 to (StringGrid1.Rows[i].Count - 1) do begin
// Si no es la primera celda, añadimos un separador
// if not is the first cell we add the separator
if (j <> 0) then begin
Str := Str + CHAR_SEP;
end;
// Construimos la cadena
// construct the string
Str := Str + StringGrid1.Rows[i].Strings[j];
end;
// La guardamos en el fichero (utilizando un TStrings, por ejemplo)
// Save to the file (using TStrings by example)
TS := TStringList.Create();
TS.Add(Str);
TS.SaveToFile('C:\aaa.txt');
TS.Free;