Delphi中从Excel导入数据的通用方法
用Delphi从excel导入数据的时候,经常都只是需要一个worksheet,然后循环读取单元格信息,存入数据库。但是,每次都要重复的写关于打开,关闭excel的application的代码。
话不多说,看代码:
TypeTExcelFunction = procedure(asheet: OleVariant);//声明导入函数
//afilename为数据源文件名,func为执行导入的函数
procedure RunExcelApplication (afilename: string; func: TExcelFunction);
var
app: OleVariant;
oldCursor: TCurSor;
begin
oldCursor := Screen.Cursor; //保存鼠标指针状态
Screen.Cursor := crHourGlass;
try
CoInitializeEx(nil, 0);
app := CreateOleObject('Excel.Application');
app.DisplayAlerts := False;
app.WorkBooks.open(afilename); //打开源文件
app.WorkSheets[1].Activate;
app.visible := False;//隐藏excel窗体
if Assigned(func) then //执行导入函数
func(app.ActiveSheet);//传递sheet给函数进行导入
app.WorkBooks.close;
app.quit;//关闭推出excel
Screen.Cursor := oldCursor;
except
on e: Exception do
begin
MessageBox(GetActiveWindow, pchar(e.message), '提示', MB_OK + MB_ICONINFORMATION);
Screen.Cursor := OldCursor;
Exit;
end;
end;
end;
关键在于定义一个以sheet:OLEVariant为参数的过程,来执行具体的导入工作。
访问单元格:sheet.cells[row,col]
转为string:vartostr(sheet.cells[row,col])
转为datetime:vartodatetime(sheet.cells[row,col])
……
最好先转化为基本类型后,再进行其他操作,可以减少一些莫名的错误。
本作品采用 知识共享署名-相同方式共享 4.0 国际许可协议 进行许可。