Версия для печати темы
Нажмите сюда для просмотра этой темы в оригинальном формате
Форум программистов > C++ Builder > Загрузка из файла в StringGrid


Автор: docwar 24.9.2006, 14:31
Привет!
Есть файл с данными, разделяемыми спец. символом "=". Надо загрузить данные опять же в StringGrid в соответствующие столбцы и колонки.
Файл выглядит примерно так:
Цитата
Привет!=Помогите=пожалуйста
Сам=не=справлюсь!


Сохраняю так:
Код
void __fastcall TForm1::Button2Click(TObject *Sender)
{
if(SaveDialog1->Execute()){
        TStringList *pStrings = new TStringList;
                for(int i=1; i <= StringGrid1->RowCount; i++)
                {
                pStrings->Add(StringGrid1->Cells[0][i] + "=" + StringGrid1->Cells[1][i] + "=" + StringGrid1->Cells[2][i]);
               }
        pStrings->SaveToFile(SaveDialog1->FileName);
        delete pStrings;
        }
}

Автор: stmamont 24.9.2006, 22:42
Что то типа этого я бы сделал:
Код

    // Не проверял. возможно ошибки в константах
                TStrings Strings;
    Strings.LoadFromFile("File.cfg");
    for(int i = 0 ; i < Strings.Count ; ++ i)
    {
        TString Str = Strings.Strings[i];

        for(int x = 0 ; x < 3 ; ++ x)
        {
            StringGrid1[x][i] = Str.SubString(0 , Str.AnsiPos("="));
            Str = Str.SubString(Str.AnsiPos("=") + 1 , Str.Length() - Str.AnsiPos("=") + 2);
        }
    }


Хотя скажу что это не по человечески помоему.

Автор: docwar 25.9.2006, 10:33
  [C++ Error] Unit1.cpp(20): E2352 Cannot create instance of abstract class 'TStrings'
  [C++ Error] Unit1.cpp(20): E2353 Class 'TStrings' is abstract because of '_fastcall TStrings::Get(int) = 0'
  [C++ Error] Unit1.cpp(20): E2459 VCL style classes must be constructed using operator new
  [C++ Error] Unit1.cpp(24): E2451 Undefined symbol 'TString'
  [C++ Error] Unit1.cpp(24): E2379 Statement missing ;
  [C++ Error] Unit1.cpp(28): E2015 Ambiguity between 'TComponent::operator IInterfaceComponentReference *()' and 'TComponent::operator IInterface *()'
  [C++ Error] Unit1.cpp(28): E2451 Undefined symbol 'Str'


:'(

Автор: ИванМ 27.9.2006, 19:28
Не так все просто, товарищи.

Код

void __fastcall TForm1::Button1Click(TObject *Sender)
{
    TStringList *pStrings = new TStringList;
    pStrings->LoadFromFile(OpenDialog1->FileName);

    char DecChar='=';

    for(int i=0;i<pStrings->Count;i++)
    {
        String str=pStrings->Strings[i];
        int ncol=0;
        for(int n=1;n<=str.Length();n++)
        {
            if(n==str.Length())
            {
                StringGrid1->Cells[ncol][i]=str;
                break;
            }
            else if(str[n]==DecChar)
            {
                StringGrid1->Cells[ncol][i]=str.SubString(1,n-1);
                ncol++;
                str.Delete(1,n);
                if(n==str.Length())
                {
                    StringGrid1->Cells[ncol][i]=str;
                    break;
                }
                n=0;
            }
        }
    }

    delete pStrings;
}


И ничего лишнего здесь нет.
А если вместо "=" сделаешь ";", то получится упрощенный обработчик csv-формата. Уже что-то полезное.

Автор: docwar 27.9.2006, 19:50
ИванМ, а как сделать, чтобы и первая строка загружалась?

Автор: ИванМ 27.9.2006, 20:45
В смысле?
У меня все строки загружаются. Не понял.

Автор: Vyacheslav 28.9.2006, 11:02
Ну вообще то у StringList есть такие свойства, как Names и Values
Цитата

Indicates the name part of strings with the form Name=Value.

__property AnsiString Names[int Index] = {read=GetName};

Description

When the list of strings for the TStrings object includes strings of the form Name=Value, read Names to access the name part of a string. Names is the name part of the string at the position indicated by Index. Index gives the position of the string, where 0 is the first string, 1 is the second string, and so on. If the string at the specified position is not of the form Name=Value, Names returns an empty string.

Strings of the form Name=Value are commonly found in .ini files. For example, here are a few strings taken from a typical .ini file:

DisplayGrid=1

SnapToGrid=1
GridSizeX=8
GridSizeY=8

The Name that identifies the string is to the left of the equal sign (=), and the current Value of the Name identifier is on the right side. There should be no spaces present before or after the equal sign.


Цитата

Represents the value part of a string associated with a given Name, on strings with the form Name=Value.

__property AnsiString Values[AnsiString Name] = {read=GetValue, write=SetValue};

Description

When the list of strings for the TStrings object includes strings of the form Name=Value, use Values to get or set the value part of a string associated with a specific name part. If the list does not contain any strings of the proper Name=Value form, or if none of those strings matches the Name index, Values returns an empty string.

Note:    The Name index is case-insensitive. That is, Values is the value part for the first occurrence of Name or an equivalent string that differs only in case. 

Strings of the form Name=Value are commonly found in .ini files. For example, here are a few strings taken from a typical .ini file:

DisplayGrid=1

SnapToGrid=1
GridSizeX=8
GridSizeY=8

The Name that identifies the string is to the left of the equal sign (=), and the current Value of the Name identifier is on the right side. There should be no spaces present before or after the equal sign.




Автор: Romikgy 28.9.2006, 12:32
Код

void __fastcall TForm1::BitBtn1Click(TObject *Sender)
{
  TStringList* sl1;
  int i;
TStringList* sl= new TStringList();
sl->LoadFromFile("sg.txt");
for (i=0;i<sl->Count;i++)
{
 sl1=new TStringList();
  sl1->Delimiter='=';
  sl1->DelimitedText=sl->Strings[i];
  StringGrid1->Rows[i]->Assign(sl1);
 sl1->Free();
 sl1=NULL;
}

sl->Free();
}

Код

файл sg.txt
Привет!=Помогите=пожалуйста
Сам=не=справлюсь!

юзайте smile

Автор: docwar 28.9.2006, 19:51
Спасибо большое за ответы! smile smile

ИванМ, Romikgy, а... ну не загружается первая строка... smile
Вот код формы:
Код
#include <vcl.h>
#pragma hdrstop

#include "Unit1.h"
//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma resource "*.dfm"
TForm1 *Form1;
//---------------------------------------------------------------------------
__fastcall TForm1::TForm1(TComponent* Owner)
        : TForm(Owner)
{
StringGrid1->ColCount = 8;
StringGrid1->RowCount = 12;
StringGrid1->Cells[0][0] = "...";       // opianiya
...                                                     // zagolovkov
StringGrid1->Cells[7][0] = "...";       // tablici
StringGrid1->FixedCols = 0;
StringGrid1->DefaultDrawing = false;
}
//---------------------------------------------------------------------------

void __fastcall TForm1::StringGrid1DrawCell(TObject *Sender, int ACol,    //centrirovanie zgolovkov tablici
      int ARow, TRect &Rect, TGridDrawState State)
{
TStringGrid *Grid = (TStringGrid *)Sender;
AnsiString nameCol = Grid->Cells[ACol][ARow];
int Align;
if(!ARow){
Align = DT_CENTER | DT_VCENTER | DT_SINGLELINE;
Grid->Canvas->Brush->Color = clBtnFace;
}
else
{
Align = DT_LEFT | DT_VCENTER | DT_SINGLELINE;
Grid->Canvas->Brush->Color = clWhite;
}
Grid->Canvas->FillRect(Rect);
TRect r = Rect;
DrawText(Grid->Canvas->Handle,nameCol.c_str(),nameCol.Length(),&r,Align);

}
//---------------------------------------------------------------------------
void __fastcall TForm1::N3Click(TObject *Sender)
{
if(OpenDialog1->Execute())
{
//TStringList *pStrings = new TStringList;
TStringList* sl1;
  int i;
TStringList* sl= new TStringList();
sl->LoadFromFile(OpenDialog1->FileName);
//sl->LoadFromFile("kjk.txt");
for (i=0;i<sl->Count;i++)
{
 sl1=new TStringList();
  sl1->Delimiter='=';
  sl1->DelimitedText=sl->Strings[i];
  StringGrid1->Rows[i]->Assign(sl1);
 sl1->Free();
 sl1=NULL;
}

sl->Free();
}
}

Автор: Romikgy 29.9.2006, 08:49
Цитата(docwar @  28.9.2006,  18:51 Найти цитируемый пост)
ну не загружается первая строка...

в исходном файле нет первевода строки в начале?

Автор: docwar 29.9.2006, 17:06
Цитата
[C++ Error] = Unit1.cpp(71):= E2316 'EditMode'= is not a =member of ='TStringGrid'
[C++ Error] = Unit1.cpp(72):= E2451 Undefined= symbol ='property'
[C++ Error] = Unit1.cpp(72):= E2379 Statement= missing ;

Это содержимое файла, который я открываю в проге. smile

Автор: Romikgy 29.9.2006, 22:43
Код

{
  TStringList* sl1;
  int i;
TStringList* sl= new TStringList();
sl->LoadFromFile("c:\\sg.txt");
StringGrid1->RowCount=sl->Count;
for (i=0;i<sl->Count;i++)
{
 sl1=new TStringList();
  sl1->Text=StringReplace(sl->Strings[i],"=","\n",(TReplaceFlags()<<rfReplaceAll));
  if (StringGrid1->ColCount<sl1->Count)
  StringGrid1->ColCount=sl1->Count;
  StringGrid1->Rows[i]->Assign(sl1);
 sl1->Free();
 sl1=NULL;
}
sl->Free();
for (i=0;i<StringGrid1->ColCount;i++)
StringGrid1->ColWidths[i]=
StringGrid1->Width/StringGrid1->ColCount;
}

Автор: docwar 30.9.2006, 08:54
Romikgy, спасибо большое! smile
Но у меня опять проблема... текст добавляется прямо в заголовок таблицы...

Автор: Romikgy 30.9.2006, 11:31
Цитата(Romikgy @  29.9.2006,  21:43 Найти цитируемый пост)
StringGrid1->RowCount=sl->Count;

StringGrid1->RowCount=sl->Count+1;
Цитата(Romikgy @  29.9.2006,  21:43 Найти цитируемый пост)
StringGrid1->Rows[i]->Assign(sl1);

StringGrid1->Rows[i+1]->Assign(sl1);

Автор: docwar 30.9.2006, 13:08
Отлично! smile Спасибо!
Только почему скроулинг добавляется горизонтальный?  smile   Т.е. последняя колонка у меня широкая, открываю файл и она становится шириной как все + остается промежуток до конца таблицы, который и прокручивается.....

Автор: Romikgy 30.9.2006, 13:11
Цитата(Romikgy @  29.9.2006,  21:43 Найти цитируемый пост)
for (i=0;i<StringGrid1->ColCount;i++)
StringGrid1->ColWidths[i]=
StringGrid1->Width/StringGrid1->ColCount;

это добавлел?

Автор: docwar 30.9.2006, 16:36
Добавлял...  появляется скроулинг и последний столбец получается такой же ширины, как и все остальные....

Автор: Romikgy 30.9.2006, 20:19
а те скролинг вообще не надо?

Автор: docwar 30.9.2006, 21:23
Допустим, что поступлю так ScrollBras->ssVertical
Но как быть с тем, что последний столбец становится шириной как все???

Добавлено @ 21:35 
Убрал гор. скроулинг, его не видно, но один раз страницу можно вертикально "листнуть"...

Автор: Romikgy 30.9.2006, 23:23
Цитата(docwar @  30.9.2006,  20:23 Найти цитируемый пост)
Но как быть с тем, что последний столбец становится шириной как все???

а что те надо?

Автор: docwar 30.9.2006, 23:42
Чтобы он остался шире всех (как и делаю в конструкторе)

Автор: Romikgy 1.10.2006, 00:23
Цитата(Romikgy @  30.9.2006,  12:11 Найти цитируемый пост)
for (i=0;i<StringGrid1->ColCount;i++)StringGrid1->ColWidths[i]=StringGrid1->Width/StringGrid1->ColCount;

тогда это ненадо

Powered by Invision Power Board (http://www.invisionboard.com)
© Invision Power Services (http://www.invisionpower.com)