千家信息网

读取excel

发表于:2024-09-23 作者:千家信息网编辑
千家信息网最后更新 2024年09月23日,procedure TfrmBuyingItems.barsaveClick(Sender: TObject);var excelx,excely : string;ExcelApp,WorkBook
千家信息网最后更新 2024年09月23日读取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;

0