Delphi - How to read entire Excel spreadsheet into a Clientdataset?

Asked

Viewed 830 times

0

Talk people! I’m having a problem reading data from an Excel spreadsheet into Olevariant objects. My file even reads the spreadsheet correctly, only it only reads up to line 3162 and the spreadsheet has 3272 lines. Is there any limit to read these Excel spreadsheets? The code is below:

procedure TfrmEnvioDeEstoque.Button1Click(Sender: TObject);
var
  Excel, Livro, Planilha, Range: OleVariant;
  Dados: Variant;
  i: Integer;
  j: Integer;
const
  xlDown = -4121;
begin
  inherited;
  opnPlanilha.Execute();

  Excel := CreateOleObject('Excel.Application');
  try
    Livro := Excel.WorkBooks.Open(opnPlanilha.FileName);
    Planilha := Livro.WorkSheets.Item['Sheet1'];

    Range := Planilha.Range['A2', Planilha.Range['O2'].End[xlDown]];
    Dados := Range.Value;

    cdsProdutos.DisableControls;
    cdsProdutos.EmptyDataSet;
    cdsProdutos.First;

    for i := 1 to VarArrayHighBound(Dados, 1) do
    begin
      cdsProdutos.Append;
      cdsProdutosmarcar.AsString       := 'T';
      cdsProdutosreferencia.AsString   := Dados[i, 1];
      cdsProdutosnome.AsString         := Dados[i, 2];
      cdsProdutossku.AsString          := Dados[i, 3];
      cdsProdutosatt1.AsString         := Dados[i, 4];
      cdsProdutosatt2.AsString         := Dados[i, 5];
      cdsProdutosatt3.AsString         := Dados[i, 6];
      cdsProdutosquantidade.AsInteger  := StrToInt(Dados[i, 7]);
      cdsProdutospreco.AsFloat         := StrToFloat(Dados[i, 8]);
      cdsProdutosvariante.AsString     := Dados[i, 9];
      cdsProdutospeso.AsString         := Dados[i, 10];
      cdsProdutoslargura.AsString      := Dados[i, 11];
      cdsProdutoscomprimento.AsString  := Dados[i, 12];
      cdsProdutosaltura.AsString       := Dados[i, 13];
      cdsProdutostags.AsString         := Dados[i, 14];
      cdsProdutoscodigoBarras.AsString := Dados[i, 15];
    end;

  finally
    Range := Unassigned;
    Planilha := Unassigned;
    Livro := Unassigned;
    Excel.Quit;
    Excel := Unassigned;

    cdsProdutos.First;
    cdsProdutos.EnableControls;
  end;

end;

My spreadsheet has columns from A to O, so I get a range for Data. This way I can popular the fields of my Clientdataset the way I’m doing above. If there’s an easier way to do that, I’d like to know. Thank you very much!

  • Try initializing a variable with the contents of Vararrayhighbound (Data, 1) and see if it is with the correct value.

  • 1

    if in the worksheet column "O" has a blank cell before line 3272 the method End(xlDown) will end up in the last row with content... use this method when you are sure that all rows are filled cells for that column, using the @Ricardoalvescarvalho tip you can easily verify this

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.