• Delphi 利用NativeExcel 实现 导入(返回clientdataset) 导出


    1、先要安装控件NativeExcel310(自行下载)

    2、添加单元引用

       uses nexcel;
    

    3、转换方法

    function ExcelToDataSet(fileNmae:string):TClientDataSet;
    var
    od: TOpenDialog;
    wb: IXLSWorkbook;
    ws: IXLSWorksheet;
    irow,J: integer;
    v: Variant;
    ClientDataSet1: TClientDataSet;
    MaxCell: Integer;
    begin
      wb := TXLSWorkbook.Create;
      wb.Open(fileNmae);
      ws := wb.WorkSheets[1];            // sheet1
      if ws.UsedRange.Rows.Count = 0 then
      Exit;
    
      if ClientDataSet1 <> nil then
        ClientDataSet1.Free;
    
      ClientDataSet1:= TClientDataSet.Create(nil);
    
      MaxCell:= 0;
      for irow := 1 to ws.UsedRange.Cells.Count - 1 do // 遍历标题
      begin
    
        v := ws.UsedRange.Cells[1, irow].Value;
        if VarIsNull(v) then
           Break;
    
        if not VarIsNull(v) then
         begin
            MaxCell:= MaxCell + 1;
            ClientDataSet1.FieldDefs.Add(v,ftstring,90 );
         end;
    
      end;
      ClientDataSet1.CreateDataSet; //建立
      ClientDataSet1.Active;
    
      ClientDataSet1.Edit;
      for J := 2 to ws.UsedRange.Rows.Count   do
      begin
    
    //      for irow := 1 to ws.UsedRange.Cells.Count - 1 do // 遍历标题
        for irow := 1 to MaxCell -1 do // 遍历标题
        begin
    
          v := VarToStr(ws.UsedRange.Cells[J, irow].Value);
    //        if not VarIsNull(v) then
          begin
    
            //根据列名Post数据
             ClientDataSet1.FieldByName(ws.UsedRange.Cells[1, irow].Value).AsString:= v;
          end;
    
        end;
          ClientDataSet1.Append;
      end;
    
    
      Result := ClientDataSet1;
    
      wb.Close;
    
    
    end;
    
    

    4、导出

    procedure TForm2.Button3Click(Sender: TObject);
    var
    xls: TDataset2Excel;
    sd: TSaveDialog;
    
    begin
      //export
    
      if ClientDataSet1 = nil then
        Exit;
      sd := TSaveDialog.Create(nil);
      sd.Filter := 'xls|*.xls';
      sd.FileName := '1.xls';
      if sd.Execute then
      begin
        xls := TDataset2Excel.Create(nil);
        xls.Dataset := ClientDataSet1;
        xls.WorksheetName := '1';
        xls.SaveDatasetAs(sd.FileName);
        xls.Workbook := nil;
        xls.Free;
      end;
      sd.Free;
    end;
    
    
  • 相关阅读:
    HDU 1754 I Hate It (线段树)
    HDU 1394 Minimum Inversion Number (树状数组)
    天梯赛 L2-012 关于堆的判断 (二叉树)
    HDU 1166 敌兵布阵 (树状数组 单点修改+区间查询)
    [leetcode-77-Combinations]
    [leetcode-101-Symmetric Tree]
    [leetcode-21-Merge Two Sorted Lists]
    [leetcode-109-Convert Sorted List to Binary Search Tree]
    [leetcode-507-Perfect Number]
    [leetcode-537-Complex Number Multiplication]
  • 原文地址:https://www.cnblogs.com/Ken2018/p/15188843.html
Copyright © 2020-2023  润新知