Как импортировать данные из Excel в StringGrid
Как импортировать данные из Excel в StringGrid
Как импортировать данные из Excel в StringGrid uses comobj; function xls_to_stringgrid(agrid: tstringgrid; axlsfile: string): boolean; const xlcelltypelastcell = $0000000b; var xlapp, sheet: olevariant; rangematrix: variant; x, y, k, r: integer; begin result := false; // create excel-ole object xlapp := createoleobject('excel.application'); try // hide excel xlapp.visible := false; // open the workbook xlapp.workbooks.open(axlsfile); // sheet := xlapp.workbooks[1].worksheets[1]; sheet := xlapp.workbooks[extractfilename(axlsfile)].worksheets[1]; // in order to know the dimension of the worksheet, i.e the number of rows // and the number of columns, we activate the last non-empty cell of it sheet.cells.specialcells(xlcelltypelastcell, emptyparam).activate; // get the value of the last row x := xlapp.activecell.row; // get the value of the last column y := xlapp.activecell.column; // set stringgrid's row &col dimensions. agrid.rowcount := x; agrid.colcount := y; // assign the variant associated with the worksheet to the delphi variant rangematrix := xlapp.range['a1', xlapp.cells.item[x, y]].value; // define the loop for filling in the tstringgrid 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; // unassign the delphi variant matrix rangematrix := unassigned; finally // quit excel if not varisempty(xlapp) then begin // xlapp.displayalerts := false; xlapp.quit; xlapp := unassigned; sheet := unassigned; result := true; end; end; end; procedure tform1.button1click(sender: tobject); begin if xls_to_stringgrid(stringgrid1, 'c:\table1.xls') then showmessage('table has been exported!'); end;