Delphi import and export Excel and Sql Server

table of Contents

Delphi import and export Excel and Sql Server

1. About ACE engine and Jet engine

1.1 Jet engine (short for Microsoft.Jet.OLEDB.4.0)

1.2, ACE pulling (Microsoft.ACE.OLEDB.12.0)

1.3, Microsoft Access 2010 database engine redistributable package (ie: Access 2010 version of ACE engine)

Overview

Installation requirements

Microsoft Access 2010 database engine installation instructions

other instructions:

2. Why use ACE engine?

2.1, Microsoft.Jet.OLEDB.4.0 engine Microsoft has not been maintaining it for a long time, and can only handle data sharing between MS Office 2003 and below and MS Sql Server

2.2. The Microsoft.ACE.OLEDB.12.0 engine is a product of ADO.Net. It is currently the only two mainstream large-scale relational database engine technologies on the market that Oracle’s ODP goes hand in hand with it.

2.3. ADO.Net and ADO are database engine technologies with completely different architectures.

3. Why does Delphi use ACE engine or Jet engine instead of OleObject or OleVariant technology based on ComObj technology?

Fourth, use ACE engine technology in Delphi control

4.1. Technical environment to be deployed

4.2, Delphi code to achieve ACE.OLEDB.12.0 import and export Excel and Sql Server

        Delphi 6 ~ Delphi 10.4.2 general code:  

        Delphi call method:  

Related to this blog:

If you like it, just click like and favorite below, so that you can watch the next sharing:


Delphi import and export Excel and Sql Server

 

1. About ACE engine and Jet engine

1.1 Jet engine (short for Microsoft.Jet.OLEDB.4.0)

        Jet.OLEDB.4.0 can only handle data sharing between MS Office 2003 and below and MS Sql Server

1.2, ACE pulling (Microsoft.ACE.OLEDB.12.0)

        ACE.OLEDB.12.0 can handle data sharing between MS Office 97~now the latest MS Office 2019 versions and MS Sql Server

1.3, Microsoft Access 2010 database engine redistributable package (ie: Access 2010 version of ACE engine)

http://www.microsoft.com/zh-CN/download/details.aspx?id=13255   , the description is as follows:

Overview

Version: sp2 Realease Date: 2019/12/20

  • This download will install a series of components to help in existing Microsoft Office files (such as Microsoft Office Access 2010 (*.mdb and *.accdb) files and Microsoft Office Excel 2010 (*.xls, *.xlsx and *.xlsb) Files) and other data sources (such as Microsoft SQL Server) to transfer data .
  • It also supports establishing a connection with existing text files .
  • In addition, ODBC and OLEDB drivers will be installed for application developers to use when developing applications that connect to the Office file format .


The Access 2010 database engine redistributable package is not used for the following purposes:

  1. As a general replacement for Jet (if you need a general replacement for Jet, you should use  SQL Server Express Edition ).
  2. As an alternative to Jet OLEDB provider for server-side applications.
  3. As a general word processing, spreadsheet or database management system-used to create documents. (You can use Microsoft Office or Office Automation to create files supported by Microsoft Office.)
  4. Used by a server-side program running under a system account by a system service or code, or will handle multiple user identities at the same time, or can be highly reentrant and expect stateless behavior. For example, a program that runs from the task scheduler when no user is logged in; or, a program that is called from a server-side Web application like ASP.NET; or, a distributed component that runs under COM+ services.

Installation requirements

Supported operating system

Windows 10, Windows 7, Windows 8, Windows Server 2003, Windows Server 2003 Service Pack 1, Windows Server 2003 Service Pack 2, Windows Server 2008 R2, Windows Server 2008 Service Pack 2, Windows Server 2012 R2, Windows Vista Service Pack 1, Windows XP Service Pack 2

  • Only 32 Access database engine can be used on Windows XP Service Pack 3if you previously installed Office, the Office is 32, then should correspond to install the 32-bit ACE; Office is 64, it should correspond installation 64 Bit of ACE.
  • AccessDatabaseEngine.exe 、AccessDatabaseEngine_X64.exe

Microsoft Access 2010 database engine installation instructions

Note: Before installing this download, you must first uninstall any previous version of the Access database engine from your computer by using "Add/Remove Programs" in the "Control Panel".

To install this download:

  1. Download the file by clicking the "Download" button and saving the file to the hard drive.
  2. Double-click the "AccessDatabaseEngine.exe" program file on the hard disk to start the installation program.
  3. Follow the instructions on the screen to complete the installation.

To use this download, please do the following: (Otherwise, you will not be able to connect successfully:)

  1. If you are an application user, please consult your application documentation for details on how to use the corresponding driver.
  2. If you are an application developer using OLEDB , please set the Provider parameter of the ConnectionString property to "Microsoft.ACE.OLEDB.12.0".
    For example: Provider=MICROSOFT.ACE.OLEDB.12.0;
    if you want to connect to Microsoft Office Excel data, please add the corresponding OLEDB connection string extended attributes according to the Excel file type:

    file type (extension) extended attributes
    ------ -------------------------------------------------- -------------------------------------
    Excel 97-2003 Workbook (.xls) "Excel 8.0 "For                      example: Extended Properties=Excel 8.0;
    Excel 2007-2010 workbook (.xlsx) "Excel 12.0 Xml" For            example: Extended Properties=Excel 12.0 Xml;
    Macro-enabled Excel 2007-2010 workbook (.xlsm) "Excel 12.0 macro "
    Excel 2007-2010 Non-XML Binary Workbook (.xlsb) "Excel 12.0"                    

    Provider=MICROSOFT.ACE.OLEDB.12.0;Data Source=D:\开发包\饲料分批次进销存-存货计价和条码\A1.xls;Extended Properties=Excel 8.0;Persist Security Info=False
    Provider=MICROSOFT.ACE.OLEDB.12.0;Data Source=D:\开发包\饲料分批次进销存-存货计价和条码\A1.xlsx;Extended Properties=Excel 12.0 Xml;Persist Security Info=False
    

    This is important!

  3. If you are an application developer who uses ODBC to connect to Microsoft Office Access data, please set the connection string to "Driver={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=path to mdb/accdb file "
  4. If you are an application developer who uses ODBC to connect to Microsoft Office Excel data, please set the connection string to "Driver={Microsoft Excel Driver (*.xls, *.xlsx, *.xlsm, *.xlsb)}; DBQ=path to xls/xlsx/xlsm/xlsb file"

To delete this download, please do the following:
To delete the download file itself, delete the file  AccessDatabaseEngine.exe

  1. On the Start menu, point to Settings, and then click Control Panel .
  2. Double-click  "Add/Remove Programs" .
  3. In the list of currently installed applications, select "Microsoft Access 2010 Database Engine" , and then click "Remove" or "Add/Remove" . If a dialog box appears, follow the instructions to remove the program.
  4. Click "Yes" or "OK" to confirm that you want to delete the program.

other instructions:

Office System drivers are only supported in certain specific situations, including:

  1. Desktop applications that read or write various file formats (including Microsoft Office Access, Microsoft Office Excel, and text files).
  2. Transfer data between supported file formats and databases (such as SQL Server). For example, use the SQL Server Import and Export Wizard or SQL Server Integration Services to import data from an Excel workbook to SQL Server (provided that the SSIS job runs in the context of a logged in user with a valid HKEY_CURRENT_USER registry hive).

2. Why use ACE engine?

2.1, Microsoft.Jet.OLEDB.4.0 engine Microsoft has not been maintaining it for a long time, and can only handle data sharing between MS Office 2003 and below and MS Sql Server

        Jet.OLEDB.4.0 can only handle data sharing between MS Office 2003 and below and MS Sql Server; and Microsoft has long no longer maintained it. It is a product of ADO.

2.2. The Microsoft.ACE.OLEDB.12.0 engine is a product of ADO.Net. It is currently the only two mainstream large-scale relational database engine technologies on the market that Oracle’s ODP goes hand in hand with it.

        ACE.OLEDB.12.0 can handle data sharing between MS Office 97 and the latest MS Office 2019 versions and MS Sql Server. Microsoft will always maintain it, and it plays an important role in the underlying data processing of the .Net strategy and the current Microsoft cloud universe database Cosmos DB and Azure operating system database. It is a product of ADO.Net.

2.3. ADO.Net and ADO are database engine technologies with completely different architectures.

 

3. Why does Delphi use ACE engine or Jet engine instead of OleObject or OleVariant technology based on ComObj technology?

        The ACE engine or Jet engine is N orders of magnitude faster than ComObj.pas' CreateOleObject.
        Because it is the native method of Microsoft's OLE database engine: it only takes about 20 seconds to export 1 million records to Excel.

Fourth, use ACE engine technology in Delphi control

4.1. Technical environment to be deployed

        See this article [1.3, Microsoft Access 2010 database engine redistributable package].

4.2, Delphi code to achieve ACE.OLEDB.12.0 import and export Excel and Sql Server

        Delphi 6 ~ Delphi 10.4.2 general code:  

//Delphi 6 ~ Delphi 10.4.2通用代码: 

function TDMGlobalFun.AceToXls( AFullPathName:string;AAce_Extended_Properties:string;
  AWorkSheet_TableName:string;AColums_DisPlayLabel:string;ASelectList:string):Integer;
var
    LFilePath: string;
    LFileExt: string;
    LFileStream: TFileStream;
    LAce_Extended_Properties: string;
    LResultLines: Integer;
    LDML_OpenDataSource_Sql:string;
    ExcelCon1: TADOConnection; ExcelDBQuery:TADOQuery;
    LTestStrings :TStringList;
begin
  LResultLines:= 1;
  if (trim(AAce_Extended_Properties)='')
    or (trim(AFullPathName)='') then LResultLines:= 0;
  if LResultLines=0 then
  begin
    Result:=LResultLines;
    exit;
  end;
  LFilePath:=SysUtils.ExtractFileDir(trim(AFullPathName)) ;
  if SysUtils.DirectoryExists(LFilePath)=false then
  begin //:如果路径不存在就强制产生路径并返回是否成功产生路径:
    if SysUtils.ForceDirectories(AFullPathName)=false then
    begin
      Application.MessageBox('路径字符串表达不合法!', '系统提示:', MB_OK);
      LResultLines:= 0;
      Result:=LResultLines;
      exit;
    end;
  end;
  LFileExt:= SysUtils.ExtractFileExt( trim(AFullPathName) );
  if (trim(LFileExt)='')
    and (trim(LFileExt)<>'.xls')
    and (trim(LFileExt)<>'.xlsx')
    and (trim(LFileExt)<>'.xlsm')
    and (trim(LFileExt)<>'.xlsb') then
  begin
    Application.MessageBox('文件的扩展名字符串表达不合法!', '系统提示:', MB_OK);
    LResultLines:= 0;
    Result:=LResultLines;
    exit;
  end else
  begin//获取正确的Excel扩展属性:
    if (trim(LFileExt)='.xls') then
      LAce_Extended_Properties:='Excel 8.0';//:Excel 97-2003 工作簿 (.xls)
    if (trim(LFileExt)='.xlsx') then
      LAce_Extended_Properties:='Excel 12.0 Xml';//:Excel 2007-2010 工作簿 (.xlsx)
    if (trim(LFileExt)='.xlsm') then
      LAce_Extended_Properties:='Excel 12.0 宏';//:启用宏的 Excel 2007-2010 工作簿 (.xlsm)
    if (trim(LFileExt)='.xlsb') then
      LAce_Extended_Properties:='Excel 12.';//:Excel 2007-2010 非 XML 二进制工作簿 (.xlsb)
  end;

  //开始用文件流产生一个Excel文件
  if SysUtils.FileExists(trim(AFullPathName))=false then
    LFileStream:= TFileStream.Create(trim(AFullPathName),Classes.fmCreate or SysUtils.fmOpenReadWrite);
  if SysUtils.FileExists(trim(AFullPathName))=true then
    if LFileStream<>nil then LFileStream.Free;
  //开始拼接MS Sql Server内部函数OPENDATASOURCE的OLEDB数据库连接的的ConnectionString:
  LTestStrings:= TStringList.Create;
  ExcelCon1:= TADOConnection.Create(nil);
  try
    {try
      ExcelCon1.LoginPrompt:= false;
      ExcelCon1.Mode:= cmShareDenyWrite;//:连接拒绝共享写:::::::::::
      ExcelCon1.KeepConnection:= true;  //:一直保持连接直至关闭
      ExcelCon1.IsolationLevel:= ilCursorStability;//:连接的冲突级别
      ExcelCon1.CursorLocation:= clUseClient;//:连接的游标位置
      ExcelCon1.ConnectOptions:= coConnectUnspecified;//:连接选项:不要异步
      ExcelCon1.CommandTimeout:= 30;//:连接超时
      ExcelCon1.ConnectionTimeout:= 15;//:连接超时
      ExcelCon1.ConnectionString
        :='Provider=MICROSOFT.ACE.OLEDB.12.0;'
        +'Data Source='+AFullPathName+';'
        +'Extended Properties='+LAce_Extended_Properties+';'
        +'Persist Security Info=False'
        ;//:连接字符串不能有换行回车符
      LTestStrings.Add(ExcelCon1.ConnectionString);
      LTestStrings.Add(LFileExt);
      LTestStrings.SaveToFile( SysUtils.ExtractFilePath(System.ParamStr(0)) +'ExcelCon1.ConnectionString.txt');
      ExcelCon1.Connected:=true;
        //:开启连接:注意!!!:同一时间只能有1个连接被打开:
          //:为什么把这段屏蔽,它与下面的连接执行DML冲突
          //:它用于Excel导入MS Sql Server时使用
    except
      LResultLines:= 0;
      LTestStrings.Free;
      if LFileStream<>nil then LFileStream.Free;
      if ExcelCon1.Connected=true then ExcelCon1.Close;
      ExcelCon1.Free;
      exit;
    end; //}
    //开始拼接OpenDataSource的DML的语句:
    LDML_OpenDataSource_Sql
      :='insert into OPENDATASOURCE ('''+'Microsoft.ACE.OLEDB.12.0'+''',' +sLineBreak
          +'''Data Source='+AFullPathName+';' +sLineBreak
              +'Extended Properties='+LAce_Extended_Properties+';'
              +'Persist Security Info=False''' +sLineBreak
      +')...['
            +Copy(SysUtils.ExtractFileName( trim(AFullPathName) ),1,LastDelimiter('.',SysUtils.ExtractFileName( trim(AFullPathName) ))-1)
         +'$](公司编码,行种子,产品编码,销量下限,销量上限,现场折扣,其它扣率,备注)' +sLineBreak
      +'select com_id,seeds_id,item_id,sd_oq_LowerLimit,sd_oq_UpperLimit,send_sum,send_sum_other,c_memo' +sLineBreak
      +'from Siliao_jxc_BarcodeStock.dbo.Ctl03001_DiscountTemp ;'
      ;
      //:Siliao_jxc_BarcodeStock:TestTemp使用全链接架构名可跨库跨域操作:
        //:比如[81.69.222.207].Carveout.dbo.sdf00504
      LTestStrings.Add(LDML_OpenDataSource_Sql);
      LTestStrings.SaveToFile( SysUtils.ExtractFilePath(System.ParamStr(0)) +'LDML_OpenDataSource_Sql.txt');
    try
      //本地当前使用的数据集curDataSet:TDataSet开始执行OpenDataSource的DML的语句:
      try
        //(curDataSet as TCustomADODataSet).Connection.BeginTrans;
          //:事务开始:Excel可能会不支持
        //(curDataSet as TAdoQuery) (curDataSet as TADOStoredProc)
        QryExec.ExecuteOptions:= [eoExecuteNoRecords];//:执行选项无需返回任何记录集
        QryExec.DisableControls;
          QryExec.SQL.Text:=LDML_OpenDataSource_Sql;
          QryExec.Prepared;
          QryExec.ExecSQL;
        QryExec.EnableControls;
        QryExec.ExecuteOptions:= [];
        //((curDataSet as TCustomADODataSet).Connection as TADOConnection)
        //LTestStrings.Add(TADOConnection(TCustomADODataSet(curDataSet).Connection).Name);//:=ADOConGlobal
        //LTestStrings.SaveToFile( SysUtils.ExtractFilePath(System.ParamStr(0)) +'LDML_OpenDataSource_Sql.txt');

      except
        //(curDataSet as TCustomADODataSet).Connection.RollbackTrans;//:事务错误回滚
        LTestStrings.Free;
        if LFileStream<>nil then LFileStream.Free;
        if ExcelCon1.Connected=true then ExcelCon1.Close;
        ExcelCon1.Free;
      end;
    finally
      //(curDataSet as TCustomADODataSet).Connection.CommitTrans; //:事务结束
    end;
    LResultLines:= 1;
  finally
    LTestStrings.Free;
    if LFileStream<>nil then LFileStream.Free;
    if ExcelCon1.Connected=true then ExcelCon1.Close;//:关闭连接
    ExcelCon1.Free; //:释放连接
    Result:= LResultLines;
  end;
end;

function TDMGlobalFun.XlsToAce( AFullPathName:string;AAce_Extended_Properties:string;
  AWorkSheet_TableName:string):Integer;
var LResultLines: Integer;  //:略了,自己参考上面的方法写:
begin
  try
    try

    except
      LResultLines:= 0;
      exit;
    end;
    LResultLines:= 1;
  finally
    Result:= LResultLines;
  end;

end;

        Delphi call method:  

procedure TfrmStoreQry.BtnPrintClick(Sender: TObject);
var LFileFullPath: string;
begin
  if DSMaster.dataset.IsEmpty then exit;
  DBGrid1.DataSource:=nil;    DBGrid1.Visible:=false;
  try
    LFileFullPath:=SysUtils.ExtractFilePath(System.ParamStr(0))+'ImportAndExport_xls\';
    //if not SysUtils.DirectoryExists(LFileFullPath) then SysUtils.ForceDirectories(LFileFullPath);
    //aDataSetToaXLS(sp_storeQry,(LFileFullPath + trim(Label5.Caption)+'.xls') );
      //:比上面基于ComObj.pas的CreateOleObject方面快得N个数量级:
        //:因为它是微软OLE数据库引擎的原生方法:100万笔记录导出Excel只需20秒左右:
        //:excel表格的Sheet中:按住CTRL键+方向键盘的下键,可得最大行数:
        //:2019版的excel表格最大行数是1048576行:
        //:2007版的excel表格最大行数是1048576行:
        //:2003版及其以下的excel表格最大行数是65536行:
    DMGlobalFun.AceToXls(
      LFileFullPath + trim(Label5.Caption)+'.xls',
      'Excel 8.0',
      trim(Label5.Caption),
      '公司编码,行种子,产品编码,销量下限,销量上限,现场折扣,其它扣率,备注',
      'com_id,seeds_id,item_id,sd_oq_LowerLimit,sd_oq_UpperLimit,send_sum,send_sum_other,c_memo'
      );
  finally
    DBGrid1.DataSource:=DSMaster;    DBGrid1.Visible:=true;
  end;
  //inherited;
end;

Related to this blog:

        1. " Delphi uses distributed query of MS Sql Server database "

        2. " RAD Studio 10.4.1 TEdgeBrowser and javascript interaction-Chromium-based Edge browser control usage 2 "

If you like it, just click like and favorite below, so that you can watch the next sharing:

 

 

 

 

 

Guess you like

Origin blog.csdn.net/pulledup/article/details/110233127