使用 OLE 方式编辑 excel 文件(原创)

使用 OLE 方式编辑 excel 文件,只要系统中双击 .xlsx 文件可以打开,就可以用 delphi 程序编辑,版本是否兼容肉眼可见。

uses
  ComObj;
 
var
  ExcelApp: variant;
  fName: string;
  i, iRowNum: Integer;
begin
  try
    try
      ExcelApp := CreateOleObject('Excel.Application');
   
      fName := ExtractFileDir(Application.ExeName) + '\Ordertemplate.xls';
      // 不显示 Excel 界面
      ExcelApp.Visible := false;
      // 禁止错误警告,当另存文件时如果文件存在,则不会提示,直接覆盖
      ExcelApp.DisplayAlerts := False;
      ExcelApp.WorkBooks.Open(fName);
   
      // 如果原文件设置了密码保护工作表,解锁
      // vba 语法类似于 ActiveSheet.Unprotect Password:="123456"
      ExcelApp.WorkSheets[1].Unprotect(Password:='123456');
   
      iRowNum := 7;
      for i := 1 to 7 do begin
        // 以工作表名称方式引用
        ExcelApp.WorkSheets['Sheet1'].Cells[iRowNum, 1].Value := 1;

        ExcelApp.WorkSheets[1].Cells[iRowNum, 2].Value := '1安全手册类';
        ExcelApp.WorkSheets[1].Cells[iRowNum, 3].Value := '101';
        ExcelApp.WorkSheets[1].Cells[iRowNum, 4].Value := Format('校园安全巡查手册%d', [i]);
        ExcelApp.WorkSheets[1].Cells[iRowNum, 5].Value := 3.25;
        iRowNum := iRowNum + 1;
      end;
      // 单元格内文字换行
      ExcelApp.WorkSheets[1].Cells[7, 2].Value := Format('1'#13#10'安全手册类', [iRowNum]);
      // 合并单元格,最好在合并前就设置单元格居中
      ExcelApp.WorkSheets[1].Range['B7:B13'].Merge;
      // 保护工作表
      ExcelApp.WorkSheets[1].Protect(Password:='123456');

      // 保存时文件名应使用全路径,否则将保存到“我的文档”中
      ExcelApp.ActiveWorkBook.SaveAs('bbbb.xls');
      ExcelApp.WorkBooks.Close;
      ExcelApp.Quit;
      ShowMessage('保存完成');
    except
      on E: Exception do begin
        ShowMessage('发生异常: ' + E.Message);
      end;
    end;
  finally
    if not VarIsNull(ExcelApp) then
      ExcelApp.Quit;
  end;
end;
posted @ 2024-08-18 11:06  汉学  阅读(97)  评论(0)    收藏  举报