Se connecter avec
S'enregistrer | Connectez-vous

Programmation avec delphi 2010

Dernière réponse : dans Programmation
Lassé par la pub ? Créez un compte
Expert Programmation

Salut,

D'après ce lien : http://www.experts-exchange.com/Programming/Languages/P...

Ce code devrait te permettre d'importer des données Excel dans un String Grid :
  1. procedure TfrmBeheerZendNota.sbtnImportFromExcelClick(Sender: TObject);
  2. var
  3. strWBName : String;
  4. strWsName : String;
  5. WorkBk : _WorkBook;
  6. WorkSheet : _WorkSheet;
  7. K, R, X, Y : Integer;
  8. intX : Integer;
  9. RangeMatrix : Variant;
  10. blnSheetExist : Boolean;
  11. begin
  12. { Initialise some variables. }
  13. strWBName := 'MyWorkBook';
  14. strWsName := 'Test';
  15. { Start Excel-Connection }
  16. XLApp.Connect;
  17. // Open the Excel File
  18. XLApp.WorkBooks.Open(strWBName,EmptyParam,EmptyParam,EmptyParam,EmptyParam,
  19. EmptyParam,EmptyParam,EmptyParam,EmptyParam,EmptyParam,
  20. EmptyParam,EmptyParam,EmptyParam,0);
  21. WorkBk := XLApp.WorkBooks.Item[1];
  22. blnSheetExist := False;
  23. intX:=1;
  24. While intX <= XLApp.Worksheets.Count do
  25. begin
  26. WorkSheet := WorkBk.Worksheets.Get_Item(intX) as _WorkSheet;
  27. if WorkSheet.Name <> strWsName then
  28. Inc(IntX)
  29. else
  30. begin
  31. blnSheetExist := True;
  32. Break;
  33. end;
  34. end;
  35.  
  36. if not blnSheetExist then
  37. begin
  38. MessageDlg('No Sheet exist with name : ' + strWsName, mtError, [mbOK], 0);
  39. end
  40. else
  41. begin
  42. WorkSheet := WorkBk.Worksheets.Get_Item(intX) as _WorkSheet;
  43. // In order to know the dimension of the WorkSheet, i.e the number of rows and the
  44. // number of columns, we activate the last non-empty cell of it
  45. WorkSheet.Activate(intX);
  46. WorkSheet.Cells.SpecialCells(xlCellTypeLastCell,EmptyParam).Activate;
  47. // Get the value of the last row + column
  48. X := XLApp.ActiveCell.Row;
  49. Y := XLApp.ActiveCell.Column;
  50. // Define the number of the columns in the TStringGrid
  51. StringGrid1.ColCount := Y;
  52. // Assign the Variant associated with the WorkSheet to the Delphi Variant Matrix
  53. RangeMatrix := XLApp.Range['A1',XLApp.Cells.Item[X,Y]].Value;
  54. // Quit Excel and Disconnect the Server
  55. XLApp.Workbooks.Close(1);
  56. XLApp.Quit;
  57. XLApp.Disconnect;
  58. // Define the loop for filling in the TStringGrid
  59. K := 1;
  60. repeat
  61. for R := 1 to Y do
  62. StringGrid1.Cells[(R - 1),(K - 1)] := RangeMatrix[K,R];
  63. Inc(K,1);
  64. StringGrid1.RowCount := K + 1;
  65. until K > X;
  66. // Unassign the Delphi Variant Matrix
  67. RangeMatrix := Unassigned;
  68. end;
  69. end;
Lassé par la pub ? Créez un compte
Tom's guide dans le monde