讀取excel

procedure TfrmBuyingItems.barsaveClick(Sender: TObject);
 var excelx,excely : string;
   ExcelApp,WorkBook:oleVariant;
   ExcelRowCount,i:integer;
begin
  OpenDialog1.Title := '請選擇正確的excel文件';
  OpenDialog1.Filter := 'Excel(*.xls)|*.xls';

  if OpenDialog1.Execute then
  begin
try

ExcelApp := CreateOleObject('Excel.Application');

WorkBook := CreateOleObject('Excel.Sheet');
WorkBook := ExcelApp.WorkBooks.Open(opendialog1.FileName);//使用opendialog對話框指定
//excel檔路徑



ExcelApp.Visible := false;

ExcelRowCount := WorkBook.WorkSheets[1].UsedRange.Rows.Count;

for i := 1 to excelrowcount + 1 do

begin

excelx := excelapp.Cells[i,1].Value;

excely := excelapp.Cells[i,2].Value;

if ((excelapp.Cells[i,1].Value = '') and (ExcelApp.Cells[i,2].Value = '')) then
//指定excel檔的第 i 行 ,第 1,2(看狀況而定)行若是爲空就退出,這樣的設定,最好是你的
//檔案力這兩行//對應數據庫中不能爲空的數據

exit

else

with adoquery1 do

begin

close;
sql.clear;
sql.add('insert into test(name,address) values(:name,:address)');
Parameters.parambyname('name').value := excelx;//excel檔的第一列插入到test表的 name欄位;
Parameters.parambyname('address').value := excely;//excel檔的第二列插入到test表的address 欄位;
execsql;

end;

end;

finally

WorkBook.Close;

ExcelApp.Quit;

ExcelApp := Unassigned;

WorkBook := Unassigned;
end;
  end;

end;sql

相關文章
相關標籤/搜索