implementation uses ComObj; {$R *.dfm} 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; 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; procedure TForm1.Button1Click(Sender: TObject); begin if Xls_To_StringGrid(StringGrid1, 'D:\Bogor.xls') then ShowMessage('Table has been exported!'); end;
Mudah dimengertikan ? Selamat Belajar para delphier
Title : Mengimport dari Excel ke Stringgrid Delphi
Description : Bagaimanakah cara mengimport dari Excel ke Stringrid ? langsung saja jawabannya dibawah ini : implementation uses ComObj; {$R *.dfm} func...
Description : Bagaimanakah cara mengimport dari Excel ke Stringrid ? langsung saja jawabannya dibawah ini : implementation uses ComObj; {$R *.dfm} func...
Kalau sheetnya 2 atau lebih itu akan error. Terutama di baris :
BalasHapus//Mengaktifkan cell khusus
Sheet.Cells.SpecialCells(xlCellTypeLastCell, EmptyParam).Activate;
dengan error :
Activate method of range class failed
Solusinya dengan mengaktifkan dulu sheetnya.