Question

I use cxGrid and I want import a excel file to cxgrid. I wrote this code a function.

But, its wrong, because cxGrid dont know RowCount and ColCount. I would like know, what can I use, what is similar? Help me! Thank you!

function Xls_To_cxGrid(AGrid: TcxGrid; AXLSFile: string): Boolean;

const
  xlCellTypeLastCell = $0000000B;
var
  XLApp, Sheet: OLEVariant;
  RangeMatrix: Variant;
  x, y, k, r: Integer;
begin
  Result := False;
  XLApp := CreateOleObject('Excel.Application');
  try
    XLApp.Visible := False;
    XLApp.Workbooks.Open(AXLSFile);
    Sheet := XLApp.Workbooks[ExtractFileName(AXLSFile)].WorkSheets[1];

    Sheet.Cells.SpecialCells(xlCellTypeLastCell, EmptyParam).Activate;
    x := XLApp.ActiveCell.Row;
    y := XLApp.ActiveCell.Column;

      AGrid.RowCount := x;
      AGrid.ColCount := y;

    RangeMatrix := XLApp.Range['A1', XLApp.Cells.Item[X, Y]].Value;
    k := 1;
    repeat
      for r := 1 to y do
        AGrid.Cells[(r - 1), (k - 1)] := RangeMatrix[K, R];
      Inc(k, 1);
      AGrid.RowCount := k + 1;
    until k > x;
    RangeMatrix := Unassigned;

  finally
    if not VarIsEmpty(XLApp) then
    begin
      XLApp.Quit;
      XLAPP := Unassigned;
      Sheet := Unassigned;
      Result := True;
    end;
  end;
end;
Was it helpful?

Solution

The cxGrid is just a container for ChartViews, TableViews, CardViews and BandedTableViews. Being a container, it does not know anything about rows and columns. Because you want to replace a StringGrid I suggest using a (non-DB) TableView.

To get a TableView...

  • ...open the grid customization form (click on "Customize..." in the grid's "Structure Navigator" in the form designer).
  • Go to the "Views" tab and click "Add View...". Choose "Table" (not "DB Table"!).
  • On the "Structure" tab right-click on the cxGrid1Level1 symbol, choose "Select View" and the new TableView.
  • You can now go back to the "Views" tab and delete the DB TableView (cxGrid1DBTableView1).

(See also the DX help topic "Grid Levels" unter the heading "Specifying Associated Grid Views".)

Instead of "RowCount" you would then use YourView.DataController.RecordCount. "ColCount" would be YourView.ColumnCount. You can access cell values with YourView.DataController.Values[...]. To speed up the populating the view I'd surround it with

YourView.DataController.BeginUpdate;
try
  YourView.DataController.RecordCount := x;
  // ...
finally
  YourView.DataController.EndUpdate;
end;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top