Delphi将excel数据导入到数据库中源码
procedure Tfrmexceltodata.Button4Click(Sender: TObject);
const
BeginRow= 1; BeginCol= 2;
var
iRE:Integer;
iRow,iCol :Integer; //列、行
MsExcel,MsExcelWorkBook,MsExcelWorkSheet:Variant;
adoquery1:TADOQuery;
sqlstr1,sqlstr2:string;
begin
Try
OpenDialog1.FileName:=’*.xls’;
if not OpenDialog1.Execute then
begin
Exit;
end;
if ExtractFileExt(OpenDialog1.FileName) <> '.xls' then
begin
MessageBox(0, '请选择正确的excel文件',PChar('提示'),MB_OK or MB_ICONWARNING);
Exit;
end;
MsExcel:=CreateOleObject('Excel.Application');
MsExcel.visible:=true;
MsExcelWorkBook:=MsExcel.WorkBooks.Open(OpenDialog1.FileName);
Except
Exit;
end;
//开始从EXCEL文件读取相关信息,并导入数据库中的“文件登记表”表
Try
Application.ProcessMessages;//防止进程阻塞
iRow:=BeginRow;
iCol:=BeginCol;
adoquery1:=TADOQuery.Create(Self);
adoquery1.Connection:=frm_main.con1;
sqlstr1:='insert into 文件登记表(编号,来文日期,来文单位,来文原编号,文件自编号,文件标题,页数,来文份数,文件大类,文件小类,文件年度,文件状态,填卡完毕,打印完毕,是否清退)';
sqlstr2:='values (:bh,:lwrq,:lwdw,:lwybh,:wjzbh,:nrzy,:ys,:lwfs,:wjdl,:wjxl,:wjnd,:wjzt,:sywb,:pswb,:sfqt)' ;
getdh1;
getlwbh; //取得文件自编号
while trim(msExcel.WorkSheets['sheet1'].Cells[iCol,iRow].value) <> '' do
begin
with adoquery1 do
begin
Close;
SQL.Clear;
SQL.Add(sqlstr1);
SQL.Add(sqlstr2);
Parameters.ParamByName('bh').Value :=StrToInt(djbh)+iCol-1;
//Parameters.ParamByName('lwrq1').Value :=dtp1.DateTime;
Parameters.ParamByName('lwrq').Value :=Trim(msExcel.WorkSheets[1].Cells[iCol,iRow].value);
Parameters.ParamByName('lwdw').Value :=Trim(msExcel.WorkSheets[1].Cells[iCol,iRow+2].value);
Parameters.ParamByName('lwybh').Value :=Trim(msExcel.WorkSheets[1].Cells[iCol,iRow+3].value);
Parameters.ParamByName('wjzbh').Value :=Trim(msExcel.WorkSheets[1].Cells[iCol,iRow+1].value);
//Parameters.ParamByName('wjzbh').Value :=lwbh+inttostr(icol-1);//Trim(msExcel.WorkSheets[1].Cells[iCol,iRow+1].value);
Parameters.ParamByName('nrzy').Value :=Trim(msExcel.WorkSheets[1].Cells[iCol,iRow+4].value);
Parameters.ParamByName('ys').Value :=1;
Parameters.ParamByName('lwfs').Value :=1;
Parameters.ParamByName('wjdl').Value :=cbb6.text;
Parameters.ParamByName('wjxl').Value :=cbb7.text;
// Parameters.ParamByName('wjnd').Value :=FormatDateTime('yyyy',now());
Paramete