程序中经常要用到导入excel数据的功能。其实通过OLE操作Excel就简单的几行代码,但记性不好,经常要用经常要找,还是作篇笔记吧。

前提是系统中先要安装好EXCEL软件。

function ImportDataFromExcel:Boolean;
var
ExcelApp: OleVariant;
WorkBook: OleVariant;
RowCount: Integer;
iRow: Integer;
begin
try
ExcelApp := CreateOleObject('Excel.Application');
except
SysFunObj.ShowInfo('没有安装EXCEL!');
exit;
end;

ExcelApp.Visible := false;
WorkBook := ExcelApp.WorkBooks.Open(OpenDialog1.FileName);
RowCount := WorkBook.WorkSheets[1].UsedRange.Rows.Count;
for iRow := 2 to RowCount do
begin
cdsImp.Append;
cdsImp.FieldByName('bigKind').Text := ExcelApp.Cells[iRow, 1].Value;
cdsImp.FieldByName('smallKind').Text := ExcelApp.Cells[iRow, 2].Value;
cdsImp.FieldByName('goodsName').Text := ExcelApp.Cells[iRow, 3].Value;
cdsImp.FieldByName('price').Text := ExcelApp.Cells[iRow, 4].Value;
cdsImp.Post;
end;
Result := True;
end;