Delphi导入Excel数据
第一种用XLSReadWriteII51
procedure TForm1.Button1Click(Sender: TObject); var s: string; rows, cols: Integer; sRow, sCol: Integer; begin sRow := 0; //开始行 sCol := 0; //开始列 if OpenDialog1.Execute() then begin XLSReadWriteII51.Filename := OpenDialog1.FileName; XLSReadWriteII51.Clear; XLSReadWriteII51.Read; rows := XLSReadWriteII51.Sheets[0].LastRow + 1; cols := XLSReadWriteII51.Sheets[0].LastCol + 1; AdvStringGrid1.RowCount := rows; AdvStringGrid1.ColCount := cols; for var r := sRow to rows - 1 do begin for var c := sCol to cols - 1 do begin AdvStringGrid1.Cells[c - sCol + 1, r - sRow] := XLSReadWriteII51.Sheets[0].AsString[c, r]; end; end; end; end;
第二种方式
uses Comobj; procedure TForm1.dxBarLargeButton1Click(Sender: TObject); const BeginRow = 1; BeginCol = 2; var iRE, I: Integer; iRow, iCol: Integer; //列、行 MsExcel, MsExcelWorkBook, MsExcelWorkSheet: Variant; begin try if not OpenDialog1.Execute then begin Exit; end; try MsExcel := CreateOleObject('Excel.Application'); except MessageBox(Self.Handle, '本机未安装Excel, 请先安装Excel再执行本操作!', '警告!', 0); Exit; end; MsExcel.visible := False; MsExcelWorkBook := MsExcel.WorkBooks.Open(OpenDialog1.FileName); except Exit; end; try iRow := BeginRow; iCol := BeginCol; I := 10000; FDMemTable1.Close; FDMemTable1.Open; while Trim(MsExcel.WorkSheets[1].Cells[iCol, iRow].value) <> '' do begin with FDMemTable1 do begin Append; FDMemTable1barcode.Value := Trim(MsExcel.WorkSheets[1].Cells[iCol, iRow + 0].value); //第一列 FDMemTable1codename.Value := Trim(MsExcel.WorkSheets[1].Cells[iCol, iRow + 1].value); //第二列 Post; end; iCol := iCol + 1; I := I + 1; Application.ProcessMessages; //防止进程阻塞 end; MsExcel.Quit; except MessageBox(Self.Handle, '数据导入失败!', '警告!', 0); MsExcel.Quit; Exit; end; MessageBox(Self.Handle, '数据导入成功!', '提示!', 0); end;
本文来自博客园,作者:liessay,转载请注明原文链接:https://www.cnblogs.com/liessay/p/18509745