Lazarus中文社区

 找回密码
 立即注册(注册审核可向QQ群索取)

QQ登录

只需一步,快速开始

版权申明
查看: 10374|回复: 1

Delphi 控制/操作 Excel 方法 大全

[复制链接]

该用户从未签到

发表于 2010-1-14 22:14:51 | 显示全部楼层 |阅读模式
刚好一个项目要用到,很方便,所以记下来
  1. [size=3](一) 使用动态创建的方法
  2. 首先创建 Excel 对象,使用ComObj:
  3. var ExcelApp: Variant;
  4. ExcelApp := CreateOleObject( 'Excel.Application' );
  5. 1) 显示当前窗口:
  6. ExcelApp.Visible := True;
  7. 2) 更改 Excel 标题栏:
  8. ExcelApp.Caption := '应用程序调用 Microsoft Excel';
  9. 3) 添加新工作簿:
  10. ExcelApp.WorkBooks.Add;
  11. 4) 打开已存在的工作簿:
  12. ExcelApp.WorkBooks.Open( 'C:\Excel\Demo.xls' );
  13. 5) 设置第2个工作表为活动工作表:
  14. ExcelApp.WorkSheets[2].Activate;   或 ExcelApp.WorksSheets[ 'Sheet2' ].Activate;
  15. 6) 给单元格赋值:
  16. ExcelApp.Cells[1,4].Value := '第一行第四列';
  17. 7) 设置指定列的宽度(单位:字符个数),以第一列为例:
  18. ExcelApp.ActiveSheet.Columns[1].ColumnsWidth := 5;
  19. 8) 设置指定行的高度(单位:磅)(1磅=0.035厘米),以第二行为例:
  20. ExcelApp.ActiveSheet.Rows[2].RowHeight := 1/0.035; // 1厘米
  21. 9) 在第8行之前插入分页符:
  22. ExcelApp.WorkSheets[1].Rows.PageBreak := 1;
  23. 10) 在第8列之前删除分页符:ExcelApp.ActiveSheet.Columns[4].PageBreak := 0;
  24. 11) 指定边框线宽度:
  25. ExcelApp.ActiveSheet.Range[ 'B3:D4' ].Borders[2].Weight := 3;
  26. 1-左     2-右    3-顶     4-底    5-斜( \ )      6-斜( / )
  27. 12) 清除第一行第四列单元格公式:
  28. ExcelApp.ActiveSheet.Cells[1,4].ClearContents;
  29. 13) 设置第一行字体属性:ExcelApp.ActiveSheet.Rows[1].Font.Name := '隶书';
  30. ExcelApp.ActiveSheet.Rows[1].Font.Color   := clBlue;
  31. ExcelApp.ActiveSheet.Rows[1].Font.Bold    := True;
  32. ExcelApp.ActiveSheet.Rows[1].Font.UnderLine := True;
  33. 14) 进行页面设置:
  34. a.页眉:
  35.     ExcelApp.ActiveSheet.PageSetup.CenterHeader := '报表演示';
  36. b.页脚:
  37.     ExcelApp.ActiveSheet.PageSetup.CenterFooter := '第&P页';
  38. c.页眉到顶端边距2cm:
  39.     ExcelApp.ActiveSheet.PageSetup.HeaderMargin := 2/0.035;
  40. d.页脚到底端边距3cm:
  41.     ExcelApp.ActiveSheet.PageSetup.HeaderMargin := 3/0.035;
  42. e.顶边距2cm:
  43.     ExcelApp.ActiveSheet.PageSetup.TopMargin := 2/0.035;
  44. f.底边距2cm:
  45.     ExcelApp.ActiveSheet.PageSetup.BottomMargin := 2/0.035;
  46. g.左边距2cm:
  47.     ExcelApp.ActiveSheet.PageSetup.LeftMargin := 2/0.035;
  48. h.右边距2cm:
  49.     ExcelApp.ActiveSheet.PageSetup.RightMargin := 2/0.035;
  50. i.页面水平居中:
  51.     ExcelApp.ActiveSheet.PageSetup.CenterHorizontally := 2/0.035;
  52. j.页面垂直居中:
  53.     ExcelApp.ActiveSheet.PageSetup.CenterVertically := 2/0.035;
  54. k.打印单元格网线:
  55.     ExcelApp.ActiveSheet.PageSetup.PrintGridLines := True;
  56. 15) 拷贝操作:
  57. a.拷贝整个工作表:    ExcelApp.ActiveSheet.Used.Range.Copy;
  58. b.拷贝指定区域:    ExcelApp.ActiveSheet.Range[ 'A1:E2' ].Copy;
  59. c.从A1位置开始粘贴:    ExcelApp.ActiveSheet.Range.[ 'A1' ].PasteSpecial;
  60. d.从文件尾部开始粘贴:    ExcelApp.ActiveSheet.Range.PasteSpecial;
  61. 16) 插入一行或一列:
  62. a. ExcelApp.ActiveSheet.Rows[2].Insert;
  63. b. ExcelApp.ActiveSheet.Columns[1].Insert;
  64. 17) 删除一行或一列:
  65. a. ExcelApp.ActiveSheet.Rows[2].Delete;
  66. b. ExcelApp.ActiveSheet.Columns[1].Delete;
  67. 18) 打印预览工作表:
  68. ExcelApp.ActiveSheet.PrintPreview;
  69. 19) 打印输出工作表:
  70. ExcelApp.ActiveSheet.PrintOut;
  71. 20) 工作表保存:
  72. if not ExcelApp.ActiveWorkBook.Saved then
  73.    ExcelApp.ActiveSheet.PrintPreview;
  74. 21) 工作表另存为:
  75. ExcelApp.SaveAs( 'C:\Excel\Demo1.xls' );
  76. 22) 放弃存盘:
  77. ExcelApp.ActiveWorkBook.Saved := True;
  78. 23) 关闭工作簿:
  79. ExcelApp.WorkBooks.Close;
  80. 24) 退出 Excel:
  81. ExcelApp.Quit;
  82. (二) 使用Delphi 控件方法
  83. 在Form中分别放入ExcelApplication, ExcelWorkbook和ExcelWorksheet。
  84. 1)   打开Excel
  85. ExcelApplication1.Connect;
  86. 2) 显示当前窗口:
  87. ExcelApplication1.Visible[0]:=True;
  88. 3) 更改 Excel 标题栏:
  89. ExcelApplication1.Caption := '应用程序调用 Microsoft Excel';
  90. 4) 添加新工作簿:
  91. ExcelWorkbook1.ConnectTo(ExcelApplication1.Workbooks.Add(EmptyParam,0));
  92. 5) 添加新工作表:
  93. var Temp_Worksheet: _WorkSheet;
  94. begin
  95. Temp_Worksheet:=ExcelWorkbook1.
  96. WorkSheets.Add(EmptyParam,EmptyParam,EmptyParam,EmptyParam,0) as _WorkSheet;
  97. ExcelWorkSheet1.ConnectTo(Temp_WorkSheet);End;
  98. 6) 打开已存在的工作簿:
  99. ExcelApplication1.Workbooks.Open (c:\a.xls
  100. EmptyParam,EmptyParam,EmptyParam,EmptyParam,
  101. EmptyParam,EmptyParam,EmptyParam,EmptyParam,
  102.     EmptyParam,EmptyParam,EmptyParam,EmptyParam,0)
  103. 7) 设置第2个工作表为活动工作表:
  104. ExcelApplication1.WorkSheets[2].Activate;   或
  105. ExcelApplication1.WorksSheets[ 'Sheet2' ].Activate;
  106. 8) 给单元格赋值:
  107. ExcelApplication1.Cells[1,4].Value := '第一行第四列';
  108. 9) 设置指定列的宽度(单位:字符个数),以第一列为例:
  109. ExcelApplication1.ActiveSheet.Columns[1].ColumnsWidth := 5;
  110. 10) 设置指定行的高度(单位:磅)(1磅=0.035厘米),以第二行为例:
  111. ExcelApplication1.ActiveSheet.Rows[2].RowHeight := 1/0.035; // 1厘米
  112. 11) 在第8行之前插入分页符:
  113. ExcelApplication1.WorkSheets[1].Rows.PageBreak := 1;
  114. 12) 在第8列之前删除分页符:
  115. ExcelApplication1.ActiveSheet.Columns[4].PageBreak := 0;
  116. 13) 指定边框线宽度:
  117. ExcelApplication1.ActiveSheet.Range[ 'B3:D4' ].Borders[2].Weight := 3;
  118. 1-左     2-右    3-顶     4-底    5-斜( \ )      6-斜( / )
  119. 14) 清除第一行第四列单元格公式:
  120. ExcelApplication1.ActiveSheet.Cells[1,4].ClearContents;
  121. 15) 设置第一行字体属性:
  122. ExcelApplication1.ActiveSheet.Rows[1].Font.Name := '隶书';
  123. ExcelApplication1.ActiveSheet.Rows[1].Font.Color   := clBlue;
  124. ExcelApplication1.ActiveSheet.Rows[1].Font.Bold    := True;
  125. ExcelApplication1.ActiveSheet.Rows[1].Font.UnderLine := True;
  126. 16) 进行页面设置:
  127. a.页眉:
  128.     ExcelApplication1.ActiveSheet.PageSetup.CenterHeader := '报表演示';
  129. b.页脚:
  130.     ExcelApplication1.ActiveSheet.PageSetup.CenterFooter := '第&P页';
  131. c.页眉到顶端边距2cm:
  132.     ExcelApplication1.ActiveSheet.PageSetup.HeaderMargin := 2/0.035;
  133. d.页脚到底端边距3cm:
  134.     ExcelApplication1.ActiveSheet.PageSetup.HeaderMargin := 3/0.035;
  135. e.顶边距2cm:
  136.     ExcelApplication1.ActiveSheet.PageSetup.TopMargin := 2/0.035;
  137. f.底边距2cm:
  138.     ExcelApplication1.ActiveSheet.PageSetup.BottomMargin := 2/0.035;
  139. g.左边距2cm:
  140.     ExcelApplication1.ActiveSheet.PageSetup.LeftMargin := 2/0.035;
  141. h.右边距2cm:
  142.     ExcelApplication1.ActiveSheet.PageSetup.RightMargin := 2/0.035;
  143. i.页面水平居中:
  144.     ExcelApplication1.ActiveSheet.PageSetup.CenterHorizontally := 2/0.035;
  145. j.页面垂直居中:
  146.     ExcelApplication1.ActiveSheet.PageSetup.CenterVertically := 2/0.035;
  147. k.打印单元格网线:
  148.     ExcelApplication1.ActiveSheet.PageSetup.PrintGridLines := True;
  149. 17) 拷贝操作:
  150. a.拷贝整个工作表:
  151.     ExcelApplication1.ActiveSheet.Used.Range.Copy;
  152. b.拷贝指定区域:
  153.     ExcelApplication1.ActiveSheet.Range[ 'A1:E2' ].Copy;
  154. c.从A1位置开始粘贴:
  155.     ExcelApplication1.ActiveSheet.Range.[ 'A1' ].PasteSpecial;
  156. d.从文件尾部开始粘贴:
  157.     ExcelApplication1.ActiveSheet.Range.PasteSpecial;
  158. 18) 插入一行或一列:
  159. a. ExcelApplication1.ActiveSheet.Rows[2].Insert;
  160. b. ExcelApplication1.ActiveSheet.Columns[1].Insert;
  161. 19) 删除一行或一列:
  162. a. ExcelApplication1.ActiveSheet.Rows[2].Delete;
  163. b. ExcelApplication1.ActiveSheet.Columns[1].Delete;
  164. 20) 打印预览工作表:
  165. ExcelApplication1.ActiveSheet.PrintPreview;
  166. 21) 打印输出工作表:
  167. ExcelApplication1.ActiveSheet.PrintOut;
  168. 22) 工作表保存:
  169. if not ExcelApplication1.ActiveWorkBook.Saved then
  170.    ExcelApplication1.ActiveSheet.PrintPreview;
  171. 23) 工作表另存为:
  172. ExcelApplication1.SaveAs( 'C:\Excel\Demo1.xls' );
  173. 24) 放弃存盘:
  174. ExcelApplication1.ActiveWorkBook.Saved := True;
  175. 25) 关闭工作簿:
  176. ExcelApplication1.WorkBooks.Close;
  177. 26) 退出 Excel:
  178. ExcelApplication1.Quit;
  179. ExcelApplication1.Disconnect;
  180. 本人 收藏[/size]
  181. [size=3]对不起我还需要一个锁定功能啊,就是输出到EXCEL后只能看,不能进行手工修改[/size]
  182. [size=3]Xl.Cells.Select;//Select All Cells
  183. Xl.Selection.Locked = True;// Lock Selected Cells[/size]
  184. [size=3]//Xl:=CreateOleObject('Excel.Application');[/size]
  185. [size=3][hr][/size]
  186. [size=3]procedure TForm1.BitBtn4Click(Sender: TObject);
  187. var
  188.    ExcelApp, Sheet: Variant;
  189. begin
  190.    if OpenDialog1.Execute then
  191.    begin
  192.      ExcelApp := CreateOleObject( 'Excel.Application' );
  193.      ExcelApp.Workbooks.Open(OpenDialog1.FileName);
  194.      Sheet     := ExcelApp.ActiveSheet;
  195.      Caption   := 'Row Count: ' + IntToStr(Sheet.UsedRange.Rows.Count);
  196.      ExcelApp.Quit;
  197.      Sheet     := Unassigned;
  198.      ExcelApp := Unassigned;
  199.    end;
  200. end;
  201. [/size]
  202. [size=3][hr][/size]
  203. [size=3]procedure CopyDbDataToExcel(Target: TDbgrid);
  204. var
  205.    iCount, jCount: Integer;
  206.    XLApp: Variant;
  207.    Sheet: Variant;
  208. begin
  209.    Screen.Cursor := crHourGlass;
  210.    if not VarIsEmpty(XLApp) then
  211.    begin
  212.      XLApp.DisplayAlerts := False;
  213.      XLApp.Quit;
  214.      VarClear(XLApp);
  215.    end;
  216.    //通过ole创建Excel对象
  217.    try
  218.      XLApp := CreateOleObject('Excel.Application');
  219.    except
  220.      Screen.Cursor := crDefault;
  221.      Exit;
  222.    end;
  223.    XLApp.WorkBooks.Add[XLWBatWorksheet];
  224.    XLApp.WorkBooks[1].WorkSheets[1].Name := '测试工作薄';
  225.    Sheet := XLApp.Workbooks[1].WorkSheets['测试工作薄'];
  226.    if not Target.DataSource.DataSet.Active then
  227.    begin
  228.       Screen.Cursor := crDefault;
  229.       Exit;
  230.    end;
  231.    Target.DataSource.DataSet.first;[/size]
  232. [size=3]   for iCount := 0 to Target.Columns.Count - 1 do
  233.    begin
  234.       Sheet.cells[1, iCount + 1] := Target.Columns.Items[iCount].Title.Caption;
  235.    end;
  236.    jCount := 1;
  237.    while not Target.DataSource.DataSet.Eof do
  238.    begin
  239.       for iCount := 0 to Target.Columns.Count - 1 do
  240.       begin
  241.         Sheet.cells[jCount + 1, iCount + 1] := Target.Columns.Items[iCount].Field.AsString;
  242.       end;
  243.       Inc(jCount);
  244.       Target.DataSource.DataSet.Next;
  245.    end;
  246.    XlApp.Visible := True;
  247.    Screen.Cursor := crDefault;
  248. end;[/size]
  249. [size=3]看看我的函数
  250. function ExportToExcel(Header: String;
  251.    vDataSet: TDataSet): Boolean;
  252. var
  253.    I,VL_I,j: integer;
  254.    S,SysPath: string;
  255.    MsExcel:Variant;
  256. begin
  257.    Result:=true;
  258.    if Application.MessageBox('您确信将数据导入到Excel吗?','提示!',MB_OKCANCEL + MB_DEFBUTTON1) = IDOK then
  259.    begin
  260.        SysPath:=ExtractFilePath(application.exename);
  261.        with TStringList.Create do
  262.        try
  263.          vDataSet.First ;
  264.          S:=S+Header;
  265.      //     system.Delete(s,1,1);
  266.          add(s);
  267.          s:=';
  268.          For I:=0 to vDataSet.fieldcount-1 do
  269.            begin
  270.              If vDataSet.fields[I].visible=true then
  271.                 S:=S+#9+vDataSet.fields[I].displaylabel;
  272.            end;
  273.          system.Delete(s,1,1);
  274.          add(s);
  275.          while not vDataSet.Eof do
  276.          begin
  277.            S := ';
  278.            for I := 0 to vDataSet.FieldCount -1 do
  279.              begin
  280.                If vDataSet.fields[I].visible=true then
  281.                   S := S + #9 + vDataSet.Fields[I].AsString;
  282.              end;
  283.            System.Delete(S, 1, 1);
  284.            Add(S);
  285.            vDataSet.Next;
  286.          end;
  287.          Try
  288.            SaveToFile(SysPath+'\Tem.xls');
  289.          Except
  290.            ShowMessage('写文件时发生保护性错误,Excel 如在运行,请先关闭!');
  291.            Result:=false;
  292.            exit;
  293.          end;
  294.        finally
  295.          Free;
  296.        end;
  297.        Try
  298.          MSExcel:=CreateOleObject('Excel.Application');
  299.        Except
  300.          ShowMessage('Excel 没有安装,请先安装!');
  301.          Result:=false;
  302.          exit;
  303.        end;
  304.        Try
  305.          MSExcel.workbooks.open(SysPath+'\Tem.xls');
  306.        Except
  307.          ShowMessage('打开临时文件时出错,请检查'+SysPath+'\Tem.xls');
  308.          Result:=false;
  309.          exit;
  310.        end;
  311.          MSExcel.visible:=True;
  312.          for VL_I :=1 to 4 do
  313.          MSExcel.Selection.Borders[VL_I].LineStyle := 0;
  314.          MSExcel.cells.select;
  315.          MSExcel.Selection.HorizontalAlignment :=3;
  316.          MSExcel.Selection.Borders[1].LineStyle := 0;[/size]
  317. [size=3]       MSExcel.Range['A1'].Select;
  318.        MSExcel.Selection.Font.Size :=24;[/size]
  319. [size=3]       J:=0 ;
  320.        for i:=0 to vdataset.fieldcount-1 do
  321.            if vDataSet.fields[I].visible   then
  322.               J:=J+1;[/size]
  323. [size=3]       VL_I :=J;
  324.        MSExcel.Range['A1:'+F_ColumnName(VL_I)+'1'].Select;
  325.        MSExcel.Range['A1:'+F_ColumnName(VL_I)+'1'].Merge;
  326.    end
  327.    else
  328.      Result:=false;
  329. end;[/size]
复制代码
回复

使用道具 举报

该用户从未签到

 楼主| 发表于 2010-1-14 22:17:18 | 显示全部楼层
学完这个你就成为excel高手了!(Delphi对Excel的所有操作)逐个试试!
  1. 一) 使用动态创建的方法
  2. 首先创建 Excel 对象,使用ComObj:
  3. var ExcelApp: Variant;
  4. ExcelApp := CreateOleObject( 'Excel.Application' );
  5. 1) 显示当前窗口:
  6. ExcelApp.Visible := True;
  7. 2) 更改 Excel 标题栏:
  8. ExcelApp.Caption := '应用程序调用 Microsoft Excel';
  9. 3) 添加新工作簿:
  10. ExcelApp.WorkBooks.Add;
  11. 4) 打开已存在的工作簿:
  12. ExcelApp.WorkBooks.Open( 'C:\\Excel\\Demo.xls' );
  13. 5) 设置第2个工作表为活动工作表:
  14. ExcelApp.WorkSheets[2].Activate;
  15. 或
  16. ExcelApp.WorksSheets[ 'Sheet2' ].Activate;
  17. 6) 给单元格赋值:
  18. ExcelApp.Cells[1,4].Value := '第一行第四列';
  19. 7) 设置指定列的宽度(单位:字符个数),以第一列为例:
  20. ExcelApp.ActiveSheet.Columns[1].ColumnsWidth := 5;
  21. 8) 设置指定行的高度(单位:磅)(1磅=0.035厘米),以第二行为例:
  22. ExcelApp.ActiveSheet.Rows[2].RowHeight := 1/0.035; // 1厘米
  23. 9) 在第8行之前插入分页符:
  24. ExcelApp.WorkSheets[1].Rows.PageBreak := 1;
  25. 10) 在第8列之前删除分页符:
  26. ExcelApp.ActiveSheet.Columns[4].PageBreak := 0;
  27. 11) 指定边框线宽度:
  28. ExcelApp.ActiveSheet.Range[ 'B3:D4' ].Borders[2].Weight := 3;
  29. 1-左 2-右 3-顶 4-底 5-斜( \\ ) 6-斜( / )
  30. 12) 清除第一行第四列单元格公式:
  31. ExcelApp.ActiveSheet.Cells[1,4].ClearContents;
  32. 13) 设置第一行字体属性:
  33. ExcelApp.ActiveSheet.Rows[1].Font.Name := '隶书';
  34. ExcelApp.ActiveSheet.Rows[1].Font.Color := clBlue;
  35. ExcelApp.ActiveSheet.Rows[1].Font.Bold := True;
  36. ExcelApp.ActiveSheet.Rows[1].Font.UnderLine := True;
  37. 14) 进行页面设置:
  38. a.页眉:
  39. ExcelApp.ActiveSheet.PageSetup.CenterHeader := '报表演示';
  40. b.页脚:
  41. ExcelApp.ActiveSheet.PageSetup.CenterFooter := '第&P页';
  42. c.页眉到顶端边距2cm:
  43. ExcelApp.ActiveSheet.PageSetup.HeaderMargin := 2/0.035;
  44. d.页脚到底端边距3cm:
  45. ExcelApp.ActiveSheet.PageSetup.HeaderMargin := 3/0.035;
  46. e.顶边距2cm:
  47. ExcelApp.ActiveSheet.PageSetup.TopMargin := 2/0.035;
  48. f.底边距2cm:
  49. ExcelApp.ActiveSheet.PageSetup.BottomMargin := 2/0.035;
  50. g.左边距2cm:
  51. ExcelApp.ActiveSheet.PageSetup.LeftMargin := 2/0.035;
  52. h.右边距2cm:
  53. ExcelApp.ActiveSheet.PageSetup.RightMargin := 2/0.035;
  54. i.页面水平居中:
  55. ExcelApp.ActiveSheet.PageSetup.CenterHorizontally := 2/0.035;
  56. j.页面垂直居中:
  57. ExcelApp.ActiveSheet.PageSetup.CenterVertically := 2/0.035;
  58. k.打印单元格网线:
  59. ExcelApp.ActiveSheet.PageSetup.PrintGridLines := True;
  60. 15) 拷贝操作:
  61. a.拷贝整个工作表:
  62. ExcelApp.ActiveSheet.Used.Range.Copy;
  63. b.拷贝指定区域:
  64. ExcelApp.ActiveSheet.Range[ 'A1:E2' ].Copy;
  65. c.从A1位置开始粘贴:
  66. ExcelApp.ActiveSheet.Range.[ 'A1' ].PasteSpecial;
  67. d.从文件尾部开始粘贴:
  68. ExcelApp.ActiveSheet.Range.PasteSpecial;
  69. 16) 插入一行或一列:
  70. a. ExcelApp.ActiveSheet.Rows[2].Insert;
  71. b. ExcelApp.ActiveSheet.Columns[1].Insert;
  72. 17) 删除一行或一列:
  73. a. ExcelApp.ActiveSheet.Rows[2].Delete;
  74. b. ExcelApp.ActiveSheet.Columns[1].Delete;
  75. 18) 打印预览工作表:
  76. ExcelApp.ActiveSheet.PrintPreview;
  77. 19) 打印输出工作表:
  78. ExcelApp.ActiveSheet.PrintOut;
  79. 20) 工作表保存:
  80. if not ExcelApp.ActiveWorkBook.Saved then
  81. ExcelApp.ActiveSheet.PrintPreview;
  82. 21) 工作表另存为:
  83. ExcelApp.SaveAs( 'C:\\Excel\\Demo1.xls' );
  84. 22) 放弃存盘:
  85. ExcelApp.ActiveWorkBook.Saved := True;
  86. 23) 关闭工作簿:
  87. ExcelApp.WorkBooks.Close;
  88. 24) 退出 Excel:
  89. ExcelApp.Quit;
  90. (二) 使用Delphi 控件方法
  91. 在Form中分别放入ExcelApplication, ExcelWorkbook和ExcelWorksheet。
  92. 1) 打开Excel
  93. ExcelApplication1.Connect;
  94. 2) 显示当前窗口:
  95. ExcelApplication1.Visible[0]:=True;
  96. 3) 更改 Excel 标题栏:
  97. ExcelApplication1.Caption := '应用程序调用 Microsoft Excel';
  98. 4) 添加新工作簿:
  99. ExcelWorkbook1.ConnectTo(ExcelApplication1.Workbooks.Add(EmptyParam,0));
  100. 5) 添加新工作表:
  101. var Temp_Worksheet: _WorkSheet;
  102. begin
  103. Temp_Worksheet:=ExcelWorkbook1.
  104. WorkSheets.Add(EmptyParam,EmptyParam,EmptyParam,EmptyParam,0) as _WorkSheet;
  105. ExcelWorkSheet1.ConnectTo(Temp_WorkSheet);
  106. End;
  107. 6) 打开已存在的工作簿:
  108. ExcelApplication1.Workbooks.Open (c:\\a.xls
  109. EmptyParam,EmptyParam,EmptyParam,EmptyParam,
  110. EmptyParam,EmptyParam,EmptyParam,EmptyParam,
  111. EmptyParam,EmptyParam,EmptyParam,EmptyParam,0)
  112. 7) 设置第2个工作表为活动工作表:
  113. ExcelApplication1.WorkSheets[2].Activate; 或
  114. ExcelApplication1.WorksSheets[ 'Sheet2' ].Activate;
  115. 8) 给单元格赋值:
  116. ExcelApplication1.Cells[1,4].Value := '第一行第四列';
  117. 9) 设置指定列的宽度(单位:字符个数),以第一列为例:
  118. ExcelApplication1.ActiveSheet.Columns[1].ColumnsWidth := 5;
  119. 10) 设置指定行的高度(单位:磅)(1磅=0.035厘米),以第二行为例:
  120. ExcelApplication1.ActiveSheet.Rows[2].RowHeight := 1/0.035; // 1厘米
  121. 11) 在第8行之前插入分页符:
  122. ExcelApplication1.WorkSheets[1].Rows.PageBreak := 1;
  123. 12) 在第8列之前删除分页符:
  124. ExcelApplication1.ActiveSheet.Columns[4].PageBreak := 0;
  125. 13) 指定边框线宽度:
  126. ExcelApplication1.ActiveSheet.Range[ 'B3:D4' ].Borders[2].Weight := 3;
  127. 1-左 2-右 3-顶 4-底 5-斜( \\ ) 6-斜( / )
  128. 14) 清除第一行第四列单元格公式:
  129. ExcelApplication1.ActiveSheet.Cells[1,4].ClearContents;
  130. 15) 设置第一行字体属性:
  131. ExcelApplication1.ActiveSheet.Rows[1].Font.Name := '隶书';
  132. ExcelApplication1.ActiveSheet.Rows[1].Font.Color := clBlue;
  133. ExcelApplication1.ActiveSheet.Rows[1].Font.Bold := True;
  134. ExcelApplication1.ActiveSheet.Rows[1].Font.UnderLine := True;
  135. 16) 进行页面设置:
  136. a.页眉:
  137. ExcelApplication1.ActiveSheet.PageSetup.CenterHeader := '报表演示';
  138. b.页脚:
  139. ExcelApplication1.ActiveSheet.PageSetup.CenterFooter := '第&P页';
  140. c.页眉到顶端边距2cm:
  141. ExcelApplication1.ActiveSheet.PageSetup.HeaderMargin := 2/0.035;
  142. d.页脚到底端边距3cm:
  143. ExcelApplication1.ActiveSheet.PageSetup.HeaderMargin := 3/0.035;
  144. e.顶边距2cm:
  145. ExcelApplication1.ActiveSheet.PageSetup.TopMargin := 2/0.035;
  146. f.底边距2cm:
  147. ExcelApplication1.ActiveSheet.PageSetup.BottomMargin := 2/0.035;
  148. g.左边距2cm:
  149. ExcelApplication1.ActiveSheet.PageSetup.LeftMargin := 2/0.035;
  150. h.右边距2cm:
  151. ExcelApplication1.ActiveSheet.PageSetup.RightMargin := 2/0.035;
  152. i.页面水平居中:
  153. ExcelApplication1.ActiveSheet.PageSetup.CenterHorizontally := 2/0.035;
  154. j.页面垂直居中:
  155. ExcelApplication1.ActiveSheet.PageSetup.CenterVertically := 2/0.035;
  156. k.打印单元格网线:
  157. ExcelApplication1.ActiveSheet.PageSetup.PrintGridLines := True;
  158. 17) 拷贝操作:
  159. a.拷贝整个工作表:
  160. ExcelApplication1.ActiveSheet.Used.Range.Copy;
  161. b.拷贝指定区域:
  162. ExcelApplication1.ActiveSheet.Range[ 'A1:E2' ].Copy;
  163. c.从A1位置开始粘贴:
  164. ExcelApplication1.ActiveSheet.Range.[ 'A1' ].PasteSpecial;
  165. d.从文件尾部开始粘贴:
  166. ExcelApplication1.ActiveSheet.Range.PasteSpecial;
  167. 18) 插入一行或一列:
  168. a. ExcelApplication1.ActiveSheet.Rows[2].Insert;
  169. b. ExcelApplication1.ActiveSheet.Columns[1].Insert;
  170. 19) 删除一行或一列:
  171. a. ExcelApplication1.ActiveSheet.Rows[2].Delete;
  172. b. ExcelApplication1.ActiveSheet.Columns[1].Delete;
  173. 20) 打印预览工作表:
  174. ExcelApplication1.ActiveSheet.PrintPreview;
  175. 21) 打印输出工作表:
  176. ExcelApplication1.ActiveSheet.PrintOut;
  177. 22) 工作表保存:
  178. if not ExcelApplication1.ActiveWorkBook.Saved then
  179.     ExcelApplication1.ActiveSheet.PrintPreview;
  180. 23) 工作表另存为:
  181. ExcelApplication1.SaveAs( 'C:\\Excel\\Demo1.xls' );
  182. 24) 放弃存盘:
  183. ExcelApplication1.ActiveWorkBook.Saved := True;
  184. 25) 关闭工作簿:
  185. ExcelApplication1.WorkBooks.Close;
  186. 26) 退出 Excel:
  187. ExcelApplication1.Quit;
  188. ExcelApplication1.Disconnect;
  189. (三) 使用Delphi 控制Excle二维图
  190. 在Form中分别放入ExcelApplication, ExcelWorkbook和ExcelWorksheet
  191. var asheet1,achart, range:variant;
  192. 1)选择当第一个工作薄第一个工作表
  193. asheet1:=ExcelApplication1.Workbooks[1].Worksheets[1];
  194. 2)增加一个二维图
  195. achart:=asheet1.chartobjects.add(100,100,200,200);
  196. 3)选择二维图的形态
  197. achart.chart.charttype:=4;
  198. 4)给二维图赋值
  199. series:=achart.chart.seriescollection;
  200. range:=sheet1!r2c3:r3c9;
  201. series.add(range,true);
  202. 5)加上二维图的标题
  203. achart.Chart.HasTitle:=True;
  204. achart.Chart.ChartTitle.Characters.Text:=’ Excle二维图’
  205. 学完这个你就成为excel高手了!^&^
  206. 下面,以Delphi为例,说明这种调用方法。
  207. Unit excel;
  208. Interface
  209. Uses
  210. Windows,Messages,SysUtils,Classes,Graphics,Controls,Forms,Dialogs,StdCtrls,ComObj,
  211. { ComObj是操作OLE对象的函数集}
  212. Type
  213. TForm1=class(TForm)
  214. Button1:TButton;
  215. Procedure Button1Click(Sender:Tobject);
  216. Private
  217. { Private declaration}
  218. Public
  219. { Public declaration }
  220. end;
  221. var
  222. Form1:Tform1;
  223. Implementation
  224. {$R *.DFM}
  225. procedure TForm1.Button1Click(sender:Tobject);
  226. var
  227. eclApp,WordBook:Variant; {声明为OLE Automation对象}
  228. xlsFileName:string;
  229. begin
  230. xlsFileName:=’ex.xls’;
  231. try
  232. {创建OLE对象:Excel Application与WordBook}
  233. eclApp:=CreateOleObject(‘Excel.Application’);
  234. WorkBook:=CreateOleObject(Excel.Sheet’);
  235. Except
  236. Application.MessageBox(‘你的机器没有安装Microsoft Excel’,
  237. ’使用Microsoft Excel’,MB_OK+MB_ICONWarning);
  238. Exit;
  239. End;
  240. Try
  241. ShowMessage(‘下面演示:新建一个XLS文件,并写入数据,并关闭它。’);
  242. WorkBook:=eclApp.workbooks.Add;
  243. EclApp.Cells(1,1):=’字符型’;
  244. EclApp.Cells(2,1):=’Excel文件’;
  245. EclApp.Cells(1,2):=’Money’;
  246. EclApp.Cells(2,2):=10.01;
  247. EclApp.Cells(1,3):=’日期型’;
  248. EclApp.Cells(2,3):=Date;
  249. WorkBook.SaveAS(xlsFileName);
  250. WorkBook.close;
  251. ShowMessage(‘下面演示:打开刚创建的XLS文件,并修改其中的内容,然后,由用户决定是否保存。’);
  252. Workbook:=eclApp.WorkBooks.Open(xlsFileName);
  253. EclApp.Cells(1,4):=’Excel文件类型’;
  254. If MessageDlg(xlsFileName+’已经被修改,是否保存?’,
  255. mtConfirmation,[mbYes,mbNo],0)=mrYes then
  256. WorkBook.Save
  257. Else
  258. WorkBook.Saved:=True; {放弃保存}
  259. Workbook.Close;
  260. EclApp.Quit; //退出Excel Application
  261. {释放Variant变量}
  262. eclApp:=Unassigned;
  263. except
  264. showMessage(‘不能正确操作Excel文件。可能是该文件已被其他程序打开,或系统错误。’);
  265. WorkBook.close;
  266. EclApp.Quit;
  267. {释放Variant变量}
  268. eclApp:=Unassigned;
  269. end;
  270. end;
  271. end
  272. --------------------------------------------
  273. 一个操作Excel的单元     
  274. 这里给出一个Excel的操作单元,函概了部分常用Excel操作,不是我写的,是从Experts-Exchange
  275. 看到后收藏起来的,给大家参考。
  276. // 该文件操作单元封装了大部分的Excel操作
  277. // use to manipulate Excel xls File
  278. // Dragon P.C. <2000.05.10>
  279. unit ExcelUnit;
  280. interface
  281. uses
  282. Dialogs, Messages, SysUtils, Grids, Cmp_Sec, ComObj, Ads_Misc;
  283. {!~Add a blank WorkSheet}
  284. Function ExcelAddWorkSheet(Excel : Variant): Boolean;
  285. {!~Close Excel}
  286. Function ExcelClose(Excel : Variant; SaveAll: Boolean): Boolean;
  287. {!~Returns the Column String Value from its integer equilavent.}
  288. Function ExcelColIntToStr(ColNum: Integer): ShortString;
  289. {!~Returns the Column Integer Value from its Alpha equilavent.}
  290. Function ExcelColStrToInt(ColStr: ShortString): Integer;
  291. {!~Close All Workbooks. All workbooks can be saved or not.}
  292. Function ExcelCloseWorkBooks(Excel : Variant; SaveAll: Boolean): Boolean;
  293. {!~Copies a range of Excel Cells to a Delphi StringGrid. If successful
  294. True is returned, False otherwise. If SizeStringGridToFit is True
  295. then the StringGrid is resized to be exactly the correct dimensions to
  296. receive the input Excel cells, otherwise the StringGrid is not resized.
  297. If ClearStringGridFirst is true then any cells outside the input range
  298. are cleared, otherwise existing values are retained. Please not that the
  299. Excel cell coordinates are "1" based and the Delphi StringGrid coordinates
  300. are zero based.}
  301. Function ExcelCopyToStringGrid(
  302. Excel : Variant;
  303. ExcelFirstRow : Integer;
  304. ExcelFirstCol : Integer;
  305. ExcelLastRow : Integer;
  306. ExcelLastCol : Integer;
  307. StringGrid : TStringGrid;
  308. StringGridFirstRow : Integer;
  309. StringGridFirstCol : Integer;
  310. {Make the StringGrid the same size as the input range}
  311. SizeStringGridToFit : Boolean;
  312. {cells outside input range in StringGrid are cleared}
  313. ClearStringGridFirst : Boolean
  314. ): Boolean;
  315. {!~Delete a WorkSheet by Name}
  316. Function ExcelDeleteWorkSheet(
  317. Excel : Variant;
  318. SheetName : ShortString): Boolean;
  319. {!~Moves the cursor to the last row and column}
  320. Function ExcelEnd(Excel : Variant): Boolean;
  321. {!~Finds A value and moves the cursor there.
  322. If the value is not found then the cursor does not move.
  323. If nothing is found then false is returned, True otherwise.}
  324. Function ExcelFind(
  325. Excel : Variant;
  326. FindString : ShortString): Boolean;
  327. {!~Finds A value in a range and moves the cursor there.
  328. If the value is not found then the cursor does not move.
  329. If nothing is found then false is returned, True otherwise.}
  330. Function ExcelFindInRange(
  331. Excel : Variant;
  332. FindString : ShortString;
  333. TopRow : Integer;
  334. LeftCol : Integer;
  335. LastRow : Integer;
  336. LastCol : Integer): Boolean;
  337. {!~Finds A value in a range and moves the cursor there. If the value is
  338. not found then the cursor does not move. If nothing is found then
  339. false is returned, True otherwise. The search directions can be defined.
  340. If you want row searches to go from left to right then SearchRight should
  341. be set to true, False otherwise. If you want column searches to go from
  342. top to bottom then SearchDown should be set to true, false otherwise.
  343. If RowsFirst is set to true then all the columns in a complete row will be
  344. searched.}
  345. Function ExcelFindValue(
  346. Excel : Variant;
  347. FindString : ShortString;
  348. TopRow : Integer;
  349. LeftCol : Integer;
  350. LastRow : Integer;
  351. LastCol : Integer;
  352. SearchRight : Boolean;
  353. SearchDown : Boolean;
  354. RowsFirst : Boolean
  355. ): Boolean;
  356. {!~Returns The First Col}
  357. Function ExcelFirstCol(Excel : Variant): Integer;
  358. {!~Returns The First Row}
  359. Function ExcelFirstRow(Excel : Variant): Integer;
  360. {!~Returns the name of the currently active worksheet
  361. as a shortstring}
  362. Function ExcelGetActiveSheetName(Excel : Variant): ShortString;
  363. {!~Gets the formula in a cell.}
  364. Function ExcelGetCellFormula(
  365. Excel : Variant;
  366. RowNum, ColNum: Integer): ShortString;
  367. {!~Returns the contents of a cell as a shortstring}
  368. Function ExcelGetCellValue(Excel : Variant; RowNum, ColNum: Integer): ShortString;
  369. {!~Returns the the current column}
  370. Function ExcelGetCol(Excel : Variant): Integer;
  371. {!~Returns the the current row}
  372. Function ExcelGetRow(Excel : Variant): Integer;
  373. {!~Moves the cursor to the last column}
  374. Function ExcelGoToLastCol(Excel : Variant): Boolean;
  375. {!~Moves the cursor to the last row}
  376. Function ExcelGoToLastRow(Excel : Variant): Boolean;
  377. {!~Moves the cursor to the Leftmost Column}
  378. Function ExcelGoToLeftmostCol(Excel : Variant): Boolean;
  379. {!~Moves the cursor to the Top row}
  380. Function ExcelGoToTopRow(Excel : Variant): Boolean;
  381. {!~Moves the cursor to Home position, i.e., A1}
  382. Function ExcelHome(Excel : Variant): Boolean;
  383. {!~Returns The Last Column}
  384. Function ExcelLastCol(Excel : Variant): Integer;
  385. {!~Returns The Last Row}
  386. Function ExcelLastRow(Excel : Variant): Integer;
  387. {!~Open the file you want to work within Excel. If you want to
  388. take advantage of optional parameters then you should use
  389. ExcelOpenFileComplex}
  390. Function ExcelOpenFile(Excel : Variant; FileName : String): Boolean;
  391. {!~Open the file you want to work within Excel. If you want to
  392. take advantage of optional parameters then you should use
  393. ExcelOpenFileComplex}
  394. Function ExcelOpenFileComplex(
  395. Excel : Variant;
  396. FileName : String;
  397. UpdateLinks : Integer;
  398. ReadOnly : Boolean;
  399. Format : Integer;
  400. Password : ShortString): Boolean;
  401. {!~Saves the range on the currently active sheet
  402. to to values only.}
  403. Function ExcelPasteValuesOnly(
  404. Excel : Variant;
  405. ExcelFirstRow : Integer;
  406. ExcelFirstCol : Integer;
  407. ExcelLastRow : Integer;
  408. ExcelLastCol : Integer): Boolean;
  409. {!~Renames a worksheet.}
  410. Function ExcelRenameSheet(
  411. Excel : Variant;
  412. OldName : ShortString;
  413. NewName : ShortString): Boolean;
  414. {!~Saves the range on the currently active sheet
  415. to a DBase 4 table.}
  416. Function ExcelSaveAsDBase4(
  417. Excel : Variant;
  418. ExcelFirstRow : Integer;
  419. ExcelFirstCol : Integer;
  420. ExcelLastRow : Integer;
  421. ExcelLastCol : Integer;
  422. OutFilePath : ShortString;
  423. OutFileName : ShortString): Boolean;
  424. {!~Saves the range on the currently active sheet
  425. to a text file.}
  426. Function ExcelSaveAsText(
  427. Excel : Variant;
  428. ExcelFirstRow : Integer;
  429. ExcelFirstCol : Integer;
  430. ExcelLastRow : Integer;
  431. ExcelLastCol : Integer;
  432. OutFilePath : ShortString;
  433. OutFileName : ShortString): Boolean;
  434. {!~Selects a range on the currently active sheet. From the
  435. current cursor position a block is selected down and to the right.
  436. The block proceeds down until an empty row is encountered. The
  437. block proceeds right until an empty column is encountered.}
  438. Function ExcelSelectBlock(
  439. Excel : Variant;
  440. FirstRow : Integer;
  441. FirstCol : Integer): Boolean;
  442. {!~Selects a range on the currently active sheet. From the
  443. current cursor position a block is selected that contains
  444. the currently active cell. The block proceeds in each
  445. direction until an empty row or column is encountered.}
  446. Function ExcelSelectBlockWhole(Excel: Variant): Boolean;
  447. {!~Selects a cell on the currently active sheet}
  448. Function ExcelSelectCell(Excel : Variant; RowNum, ColNum: Integer): Boolean;
  449. {!~Selects a range on the currently active sheet}
  450. Function ExcelSelectRange(
  451. Excel : Variant;
  452. FirstRow : Integer;
  453. FirstCol : Integer;
  454. LastRow : Integer;
  455. LastCol : Integer): Boolean;
  456. {!~Selects an Excel Sheet By Name}
  457. Function ExcelSelectSheetByName(Excel : Variant; SheetName: String): Boolean;
  458. {!~Sets the formula in a cell. Remember to include the equals sign "=".
  459. If the function fails False is returned, True otherwise.}
  460. Function ExcelSetCellFormula(
  461. Excel : Variant;
  462. FormulaString : ShortString;
  463. RowNum, ColNum: Integer): Boolean;
  464. {!~Sets the contents of a cell as a shortstring}
  465. Function ExcelSetCellValue(
  466. Excel : Variant;
  467. RowNum, ColNum: Integer;
  468. Value : ShortString): Boolean;
  469. {!~Sets a Column Width on the currently active sheet}
  470. Function ExcelSetColumnWidth(
  471. Excel : Variant;
  472. ColNum : Integer;
  473. ColumnWidth: Integer): Boolean;
  474. {!~Set Excel Visibility}
  475. Function ExcelSetVisible(
  476. Excel : Variant;
  477. IsVisible: Boolean): Boolean;
  478. {!~Saves the range on the currently active sheet
  479. to values only.}
  480. Function ExcelValuesOnly(
  481. Excel : Variant;
  482. ExcelFirstRow : Integer;
  483. ExcelFirstCol : Integer;
  484. ExcelLastRow : Integer;
  485. ExcelLastCol : Integer): Boolean;
  486. {!~Returns the Excel Version as a ShortString.}
  487. Function ExcelVersion(Excel: Variant): ShortString;
  488. Function IsBlockColSide(
  489. Excel : Variant;
  490. RowNum: Integer;
  491. ColNum: Integer): Boolean; Forward;
  492. unction IsBlockRowSide(
  493. Excel : Variant;
  494. RowNum: Integer;
  495. ColNum: Integer): Boolean; Forward;
  496.  
  497. implementation
  498.  
  499. type
  500. //Declare the constants used by Excel
  501. SourceType = (xlConsolidation, xlDatabase, xlExternal, xlPivotTable);
  502. Orientation = (xlHidden, xlRowField, xlColumnField, xlPageField, xlDataField);
  503. RangeEnd = (NoValue, xlToLeft, xlToRight, xlUp, xlDown);
  504. ExcelPasteType = (xlAllExceptBorders,xlNotes,xlFormats,xlValues,xlFormulas,xlAll);
  505. {CAUTION!!! THESE OUTPUTS ARE ALL GARBLED! YOU SELECT xlDBF3 AND EXCEL
  506. OUTPUTS A xlCSV.}
  507. FileFormat = (xlAddIn, xlCSV, xlCSVMac, xlCSVMSDOS, xlCSVWindows, xlDBF2,
  508. xlDBF3, xlDBF4, xlDIF, xlExcel2, xlExcel3, xlExcel4,
  509. xlExcel4Workbook, xlIntlAddIn, xlIntlMacro, xlNormal,
  510. xlSYLK, xlTemplate, xlText, xlTextMac, xlTextMSDOS,
  511. xlTextWindows, xlTextPrinter, xlWK1, xlWK3, xlWKS,
  512. xlWQ1, xlWK3FM3, xlWK1FMT, xlWK1ALL);
  513. {Add a blank WorkSheet}
  514. Function ExcelAddWorkSheet(Excel : Variant): Boolean;
  515. Begin
  516. Result := True;
  517. Try
  518. Excel.Worksheets.Add;
  519. Except
  520. MessageDlg('Unable to add a new worksheet', mtError, [mbOK], 0);
  521. Result := False;
  522. End;
  523. End;
  524. {Sets Excel Visibility}
  525. Function ExcelSetVisible(Excel : Variant;IsVisible: Boolean): Boolean;
  526. Begin
  527. Result := True;
  528. Try
  529. Excel.Visible := IsVisible;
  530. Except
  531. MessageDlg('Unable to Excel Visibility', mtError, [mbOK], 0);
  532. Result := False;
  533. End;
  534. End;
  535. {Close Excel}
  536. Function ExcelClose(Excel : Variant; SaveAll: Boolean): Boolean;
  537. Begin
  538. Result := True;
  539. Try
  540. ExcelCloseWorkBooks(Excel, SaveAll);
  541. Excel.Quit;
  542. Except
  543. MessageDlg('Unable to Close Excel', mtError, [mbOK], 0);
  544. Result := False;
  545. End;
  546. End;
  547. {Close All Workbooks. All workbooks can be saved or not.}
  548. Function ExcelCloseWorkBooks(Excel : Variant; SaveAll: Boolean): Boolean;
  549. var
  550. loop: byte;
  551. Begin
  552. Result := True;
  553. Try
  554. For loop := 1 to Excel.Workbooks.Count Do
  555. Excel.Workbooks[1].Close[SaveAll];
  556. Except
  557. Result := False;
  558. End;
  559. End;
  560. {Selects an Excel Sheet By Name}
  561. Function ExcelSelectSheetByName(Excel : Variant; SheetName: String): Boolean;
  562. Begin
  563. Result := True;
  564. Try
  565. Excel.Sheets[SheetName].Select;
  566. Except
  567. Result := False;
  568. End;
  569. End;
  570. {Selects a cell on the currently active sheet}
  571. Function ExcelSelectCell(Excel : Variant; RowNum, ColNum: Integer): Boolean;
  572. Begin
  573. Result := True;
  574. Try
  575. Excel.ActiveSheet.Cells[RowNum, ColNum].Select;
  576. Except
  577. Result := False;
  578. End;
  579. End;
  580. {Returns the contents of a cell as a shortstring}
  581. Function ExcelGetCellValue(Excel : Variant; RowNum, ColNum: Integer): ShortString;
  582. Begin
  583. Result := '';
  584. Try
  585. Result := Excel.Cells[RowNum, ColNum].Value;
  586. Except
  587. Result := '';
  588. End;
  589. End;
  590. {Returns the the current row}
  591. Function ExcelGetRow(Excel : Variant): Integer;
  592. Begin
  593. Result := 1;
  594. (一) 使用动态创建的方法
  595. 首先创建 Excel 对象,使用ComObj:
  596.   var ExcelApp: Variant;
  597.   ExcelApp := CreateOleObject( 'Excel.Application' );
  598. 1) 显示当前窗口:
  599.   ExcelApp.Visible := True;
  600. 2) 更改 Excel 标题栏:
  601.   ExcelApp.Caption := '应用程序调用 Microsoft Excel';
  602. 3) 添加新工作簿:
  603.   ExcelApp.WorkBooks.Add;
  604. 4) 打开已存在的工作簿:
  605.   ExcelApp.WorkBooks.Open( 'C:\\Excel\\Demo.xls' );
  606. 5) 设置第2个工作表为活动工作表:
  607.   ExcelApp.WorkSheets[2].Activate;  或
  608.   ExcelApp.WorksSheets[ 'Sheet2' ].Activate;
  609. 6) 给单元格赋值:
  610.   ExcelApp.Cells[1,4].Value := '第一行第四列';
  611. 7) 设置指定列的宽度(单位:字符个数),以第一列为例:
  612.   ExcelApp.ActiveSheet.Columns[1].ColumnsWidth := 5;
  613. 8) 设置指定行的高度(单位:磅)(1磅=0.035厘米),以第二行为例:
  614.   ExcelApp.ActiveSheet.Rows[2].RowHeight := 1/0.035; // 1厘米
  615. 9) 在第8行之前插入分页符:
  616.   ExcelApp.WorkSheets[1].Rows[8].PageBreak := 1;
  617. 10) 在第8列之前删除分页符:
  618.   ExcelApp.ActiveSheet.Columns[4].PageBreak := 0;
  619. 11) 指定边框线宽度:
  620.   ExcelApp.ActiveSheet.Range[ 'B3:D4' ].Borders[2].Weight := 3;
  621.   1-左    2-右   3-顶    4-底   5-斜( \\ )     6-斜( / )
  622. 12) 清除第一行第四列单元格公式:
  623.   ExcelApp.ActiveSheet.Cells[1,4].ClearContents;
  624. 13) 设置第一行字体属性:
  625.   ExcelApp.ActiveSheet.Rows[1].Font.Name := '隶书';
  626.   ExcelApp.ActiveSheet.Rows[1].Font.Color  := clBlue;
  627.   ExcelApp.ActiveSheet.Rows[1].Font.Bold   := True;
  628.   ExcelApp.ActiveSheet.Rows[1].Font.UnderLine := True;
  629. 14) 进行页面设置:
  630. a.页眉:
  631.   ExcelApp.ActiveSheet.PageSetup.CenterHeader := '报表演示';
  632. b.页脚:
  633.   ExcelApp.ActiveSheet.PageSetup.CenterFooter := '第&P页';
  634. c.页眉到顶端边距2cm:
  635.   ExcelApp.ActiveSheet.PageSetup.HeaderMargin := 2/0.035;
  636. d.页脚到底端边距3cm:
  637.   ExcelApp.ActiveSheet.PageSetup.HeaderMargin := 3/0.035;
  638. e.顶边距2cm:
  639.   ExcelApp.ActiveSheet.PageSetup.TopMargin := 2/0.035;
  640. f.底边距2cm:
  641.   ExcelApp.ActiveSheet.PageSetup.BottomMargin := 2/0.035;
  642. g.左边距2cm:
  643.   ExcelApp.ActiveSheet.PageSetup.LeftMargin := 2/0.035;
  644. h.右边距2cm:
  645.   ExcelApp.ActiveSheet.PageSetup.RightMargin := 2/0.035;
  646. i.页面水平居中:
  647.   ExcelApp.ActiveSheet.PageSetup.CenterHorizontally := 2/0.035;
  648. j.页面垂直居中:
  649.   ExcelApp.ActiveSheet.PageSetup.CenterVertically := 2/0.035;
  650. k.打印单元格网线:
  651.   ExcelApp.ActiveSheet.PageSetup.PrintGridLines := True;
  652. 15) 拷贝操作:
  653. a.拷贝整个工作表:
  654.   ExcelApp.ActiveSheet.Used.Range.Copy;
  655. b.拷贝指定区域:
  656.   ExcelApp.ActiveSheet.Range[ 'A1:E2' ].Copy;
  657. c.从A1位置开始粘贴:
  658.   ExcelApp.ActiveSheet.Range.[ 'A1' ].PasteSpecial;
  659. d.从文件尾部开始粘贴:
  660.   ExcelApp.ActiveSheet.Range.PasteSpecial;
  661. 16) 插入一行或一列:
  662. a. ExcelApp.ActiveSheet.Rows[2].Insert;
  663. b. ExcelApp.ActiveSheet.Columns[1].Insert;
  664. 17) 删除一行或一列:
  665. a. ExcelApp.ActiveSheet.Rows[2].Delete;
  666. b. ExcelApp.ActiveSheet.Columns[1].Delete;
  667. 18) 打印预览工作表:
  668.   ExcelApp.ActiveSheet.PrintPreview;
  669. 19) 打印输出工作表:
  670.   ExcelApp.ActiveSheet.PrintOut;
  671. 20) 工作表保存:
  672.   if not ExcelApp.ActiveWorkBook.Saved then
  673.   ExcelApp.ActiveSheet.PrintPreview;
  674. 21) 工作表另存为:
  675.   ExcelApp.SaveAs( 'C:\\Excel\\Demo1.xls' );
  676. 22) 放弃存盘:
  677.   ExcelApp.ActiveWorkBook.Saved := True;
  678. 23) 关闭工作簿:
  679.   ExcelApp.WorkBooks.Close;
  680. 24) 退出 Excel:
  681.   ExcelApp.Quit;
  682. (二) 使用Delphi 控件方法
  683.   在Form中分别放入ExcelApplication, ExcelWorkbook和ExcelWorksheet。
  684. 1)  打开Excel
  685.   ExcelApplication1.Connect;
  686. 2) 显示当前窗口:
  687.   ExcelApplication1.Visible[0]:=True;
  688. 3) 更改 Excel 标题栏:
  689.   ExcelApplication1.Caption := '应用程序调用 Microsoft Excel';
  690. 4) 添加新工作簿:
  691.   ExcelWorkbook1.ConnectTo(ExcelApplication1.Workbooks.Add(EmptyParam,0));
  692. 5) 添加新工作表:
  693.   var Temp_Worksheet: _WorkSheet;
  694.   begin
  695.     Temp_Worksheet:=ExcelWorkbook1.WorkSheets.Add(EmptyParam,EmptyParam,EmptyParam,EmptyParam,0) as _WorkSheet;
  696.     ExcelWorkSheet1.ConnectTo(Temp_WorkSheet);
  697.   End;
  698. 6) 打开已存在的工作簿:
  699.   ExcelApplication1.Workbooks.Open (c:\\a.xls
  700.   EmptyParam,EmptyParam,EmptyParam,EmptyParam,
  701.   EmptyParam,EmptyParam,EmptyParam,EmptyParam,
  702.   EmptyParam,EmptyParam,EmptyParam,EmptyParam,0)
  703. 7) 设置第2个工作表为活动工作表:
  704.   ExcelApplication1.WorkSheets[2].Activate;  或
  705.   ExcelApplication1.WorksSheets[ 'Sheet2' ].Activate;
  706. 8) 给单元格赋值:
  707.   ExcelApplication1.Cells[1,4].Value := '第一行第四列';
  708. 9) 设置指定列的宽度(单位:字符个数),以第一列为例:
  709.   ExcelApplication1.ActiveSheet.Columns[1].ColumnsWidth := 5;
  710. 10) 设置指定行的高度(单位:磅)(1磅=0.035厘米),以第二行为例:
  711.   ExcelApplication1.ActiveSheet.Rows[2].RowHeight := 1/0.035; // 1厘米
  712. 11) 在第8行之前插入分页符:
  713.   ExcelApplication1.WorkSheets[1].Rows[8].PageBreak := 1;
  714. 12) 在第8列之前删除分页符:
  715.   ExcelApplication1.ActiveSheet.Columns[4].PageBreak := 0;
  716. 13) 指定边框线宽度:
  717.   ExcelApplication1.ActiveSheet.Range[ 'B3:D4' ].Borders[2].Weight := 3;
  718.   1-左    2-右   3-顶    4-底   5-斜( \\ )     6-斜( / )
  719. 14) 清除第一行第四列单元格公式:
  720.   ExcelApplication1.ActiveSheet.Cells[1,4].ClearContents;
  721. 15) 设置第一行字体属性:
  722.   ExcelApplication1.ActiveSheet.Rows[1].Font.Name := '隶书';
  723.   ExcelApplication1.ActiveSheet.Rows[1].Font.Color  := clBlue;
  724.   ExcelApplication1.ActiveSheet.Rows[1].Font.Bold   := True;
  725.   ExcelApplication1.ActiveSheet.Rows[1].Font.UnderLine := True;
  726. 16) 进行页面设置:
  727. a.页眉:
  728.   ExcelApplication1.ActiveSheet.PageSetup.CenterHeader := '报表演示';
  729. b.页脚:
  730.   ExcelApplication1.ActiveSheet.PageSetup.CenterFooter := '第&P页';
  731. c.页眉到顶端边距2cm:
  732.   ExcelApplication1.ActiveSheet.PageSetup.HeaderMargin := 2/0.035;
  733. d.页脚到底端边距3cm:
  734.   ExcelApplication1.ActiveSheet.PageSetup.HeaderMargin := 3/0.035;
  735. e.顶边距2cm:
  736.   ExcelApplication1.ActiveSheet.PageSetup.TopMargin := 2/0.035;
  737. f.底边距2cm:
  738.   ExcelApplication1.ActiveSheet.PageSetup.BottomMargin := 2/0.035;
  739. g.左边距2cm:
  740.   ExcelApplication1.ActiveSheet.PageSetup.LeftMargin := 2/0.035;
  741. h.右边距2cm:
  742.   ExcelApplication1.ActiveSheet.PageSetup.RightMargin := 2/0.035;
  743. i.页面水平居中:
  744.   ExcelApplication1.ActiveSheet.PageSetup.CenterHorizontally := 2/0.035;
  745. j.页面垂直居中:
  746.   ExcelApplication1.ActiveSheet.PageSetup.CenterVertically := 2/0.035;
  747. k.打印单元格网线:
  748.   ExcelApplication1.ActiveSheet.PageSetup.PrintGridLines := True;
  749. 17) 拷贝操作:
  750. a.拷贝整个工作表:
  751.   ExcelApplication1.ActiveSheet.Used.Range.Copy;
  752. b.拷贝指定区域:
  753.   ExcelApplication1.ActiveSheet.Range[ 'A1:E2' ].Copy;
  754. c.从A1位置开始粘贴:
  755.   ExcelApplication1.ActiveSheet.Range.[ 'A1' ].PasteSpecial;
  756. d.从文件尾部开始粘贴:
  757.   ExcelApplication1.ActiveSheet.Range.PasteSpecial;
  758. 18) 插入一行或一列:
  759. a. ExcelApplication1.ActiveSheet.Rows[2].Insert;
  760. b. ExcelApplication1.ActiveSheet.Columns[1].Insert;
  761. 19) 删除一行或一列:
  762. a. ExcelApplication1.ActiveSheet.Rows[2].Delete;
  763. b. ExcelApplication1.ActiveSheet.Columns[1].Delete;
  764. 20) 打印预览工作表:
  765.   ExcelApplication1.ActiveSheet.PrintPreview;
  766. 21) 打印输出工作表:
  767.   ExcelApplication1.ActiveSheet.PrintOut;
  768. 22) 工作表保存:
  769.   if not ExcelApplication1.ActiveWorkBook.Saved then
  770.     ExcelApplication1.ActiveSheet.PrintPreview;
  771. 23) 工作表另存为:
  772.   ExcelApplication1.SaveAs( 'C:\\Excel\\Demo1.xls' );
  773. 24) 放弃存盘:
  774.   ExcelApplication1.ActiveWorkBook.Saved := True;
  775. 25) 关闭工作簿:
  776.   ExcelApplication1.WorkBooks.Close;
  777. 26) 退出 Excel:
  778.   ExcelApplication1.Quit;
  779.   ExcelApplication1.Disconnect;
  780. (三) 使用Delphi 控制Excle二维图
  781.   在Form中分别放入ExcelApplication, ExcelWorkbook和ExcelWorksheet
  782.   var asheet1,achart, range:variant;
  783. 1)选择当第一个工作薄第一个工作表
  784.   asheet1:=ExcelApplication1.Workbooks[1].Worksheets[1];
  785. 2)增加一个二维图
  786.   achart:=asheet1.chartobjects.add(100,100,200,200);
  787. 3)选择二维图的形态
  788.   achart.chart.charttype:=4;
  789. 4)给二维图赋值
  790.   series:=achart.chart.seriescollection;
  791.   range:=sheet1!r2c3:r3c9;
  792.   series.add(range,true);
  793. 5)加上二维图的标题
  794.   achart.Chart.HasTitle:=True;
  795.   achart.Chart.ChartTitle.Characters.Text:=’ Excle二维图’           
  796. 6)改变二维图的标题字体大小
  797.   achart.Chart.ChartTitle.Font.size:=6;
  798. 7)给二维图加下标说明
  799.   achart.Chart.Axes(xlCategory, xlPrimary).HasTitle := True;
  800.   achart.Chart.Axes(xlCategory, xlPrimary).AxisTitle.Characters.Text := '下标说明';
  801. 8)给二维图加左标说明
  802.   achart.Chart.Axes(xlValue, xlPrimary).HasTitle := True;
  803.   achart.Chart.Axes(xlValue, xlPrimary).AxisTitle.Characters.Text := '左标说明';
  804. 9)给二维图加右标说明
  805.   achart.Chart.Axes(xlValue, xlSecondary).HasTitle := True;
  806.   achart.Chart.Axes(xlValue, xlSecondary).AxisTitle.Characters.Text := '右标说明';
  807. 10)改变二维图的显示区大小
  808.   achart.Chart.PlotArea.Left := 5;
  809.   achart.Chart.PlotArea.Width := 223;
  810.   achart.Chart.PlotArea.Height := 108;
  811. 11)给二维图坐标轴加上说明
  812.   achart.chart.seriescollection[1].NAME:='坐标轴说明';
  813. 提供在DELPHI中用程序实现EXCEL单元格合并的源码
  814. Begin
  815. CapStr:=trim(exApp.Cells[Row,1].value);
  816. Col1:=2;
  817. Col2:=FldCount;
  818. For Col1:=2 to Col2 Do
  819. begin
  820.    NewCapStr:=trim(exApp.Cells[Row,Col1].value);
  821.    if (NewCapStr=CapStr) then
  822.    Begin
  823.      Cell1:=exApp.Cells.Item[Row,Col1-1];
  824.      Cell2:=exApp.Cells.Item[Row,Col1];
  825.      exApp.Cells[Row,Col1].value:='';
  826.      exApp.Range[Cell1,Cell2].Merge(True);
  827.    end
  828.    else
  829.    begin
  830.      CapStr:=NewCapStr;
  831.    end;
  832. end;
  833. end;
  834. 数据库图片插入到excel中uses:clipbrd
  835. var
  836. MyFormat:Word;
  837. AData:THandle;      //临时句柄变量。
  838. APalette:HPALETTE;  //临时变量。
  839. Stream1:TMemoryStream;//TBlobStream
  840. xx:tbitmap;
  841.          Stream1:= TMemoryStream.Create;
  842.          TBlobField(query.FieldByName('存储图片的字段')).SaveToStream(Stream1);
  843.          Stream1.Position :=0;
  844.          xx:=tbitmap.Create ;
  845.          xx.LoadFromStream(Stream1);
  846.          xx.SaveToClipboardFormat(MyFormat,AData,APalette);
  847.          ClipBoard.SetAsHandle(MyFormat, AData);
  848.          myworksheet1.Range['g3','h7'].select;//myworksheet1是当前活动的sheet页
  849.          myworksheet1.Paste;   
  850. 程序中写的一个例子,导出库存到Excel中。
  851. 可参看有关Excel操作部分
  852. procedure TfrmExcel.StoreToExcel;
  853. var
  854. data: TADODataSet;
  855. ExcelApp, Ra:Variant;
  856. row: Integer;
  857. begin
  858. if not InitExcel(ExcelApp) then
  859.    exit;
  860. data := TADODataSet.Create(nil);
  861. data.Connection := ADOConn;
  862. try
  863.    data.CommandText := 'select * from ProInfo';
  864.    data.Open;
  865.    with TADODataSet.Create(nil) do
  866.    begin
  867.      Connection := ADOConn;
  868.      CommandText := 'select ProNO, sum(ProNum) as sNum from AreaProInfo group by ProNO';
  869.      Open;
  870.      row := 1;
  871.      ExcelApp.Rows[row].RowHeight := 30;
  872.      Ra := ExcelApp.Range[ExcelApp.Cells[row, 1], ExcelApp.Cells[row, 7]];
  873.      Ra.font.size := 18;
  874.      Ra.font.Bold := true;
  875.      Ra.MergeCells := true;
  876.      Ra.HorizontalAlignment := xlcenter;
  877.      Ra.VerticalAlignment := xlcenter;
  878.      ExcelApp.Cells[row, 1] := '部件库存情况表';
  879.      inc(row);
  880.      Ra := ExcelApp.Range[ExcelApp.Cells[row, 1], ExcelApp.Cells[row, 7]];
  881.      Ra.font.size := 10;
  882.      Ra.HorizontalAlignment := xlRight;
  883.      Ra.VerticalAlignment := xlcenter;
  884.      Ra.MergeCells := true;
  885.      ExcelApp.Cells[row, 1] := FormatDateTime('yyyy-mm-dd', Now);
  886.      inc(row);
  887.      ExcelApp.Cells[row, 1] := '部件编号';
  888.      ExcelApp.Cells[row, 2] := '部件名称';
  889.      ExcelApp.Columns[2].ColumnWidth := 15;
  890.      ExcelApp.Cells[row, 3] := '单位';
  891.      ExcelApp.Columns[3].ColumnWidth := 4;
  892.      ExcelApp.Cells[row, 4] := '型号规格';
  893.      ExcelApp.Columns[4].ColumnWidth := 20;
  894.      ExcelApp.Cells[row, 5] := '部件单价';
  895.      ExcelApp.Cells[row, 6] := '库存数量';
  896.      ExcelApp.Cells[row, 7] := '库存金额';
  897.      while not Eof do
  898.      begin
  899.        if data.Locate('ProNO', FieldByName('ProNO').AsString, []) then
  900.        begin
  901.          inc(row);
  902.          ExcelApp.Cells[row, 1] := FieldByName('ProNO').AsString;
  903.          ExcelApp.Cells[row, 2] := data.FieldByName('ProName').AsString;
  904.          ExcelApp.Cells[row, 3] := data.FieldByName('ProUnit').AsString;
  905.          ExcelApp.Cells[row, 4] := data.FieldByName('ProKind').AsString;
  906.          ExcelApp.Cells[row, 5] := data.FieldByName('ProMoney').AsString;
  907.          ExcelApp.Cells[row, 6] := FieldByName('sNum').Value;
  908.          ExcelApp.Cells[row, 7] := '=E' + IntToStr(row) + '*F' + IntToStr(row);
  909.        end;
  910.        Next;
  911. {        if RecNO = 10 then
  912.          Break;}
  913.        ProgressBar.Position := RecNO * 100 div RecordCount;
  914.        Show;
  915.      end;
  916.      ExcelApp.Cells[row + 1, 2] := '合计';
  917.      ExcelApp.Cells[row + 1, 7] := '=SUM(G2:G' + IntToStr(Row);
  918.      Free;
  919.    end;
  920. finally
  921.    data.Free;
  922.    ExcelApp.ScreenUpdating := true;
  923. end;
  924. end;
  925. function TfrmExcel.InitExcel(var excel: Variant): Boolean;
  926. begin
  927. try
  928.    excel := CreateOleObject('Excel.Application');
  929. except
  930.    result := false;
  931.    showMsg('调用Excel出错!');
  932.    exit;
  933. end;
  934. excel.WorkBooks.Add;
  935. excel.WorkSheets[1].Activate;
  936. excel.Visible := true;
  937. excel.ScreenUpdating := false;
  938. excel.Rows.RowHeight := 18;
  939. excel.ActiveSheet.PageSetup.PrintGridLines := false;
  940. result := true;
  941. end;
复制代码
回复 支持 反对

使用道具 举报

*滑块验证:

本版积分规则

QQ|手机版|小黑屋|Lazarus中国|Lazarus中文社区 ( 鄂ICP备16006501号-1 )

GMT+8, 2026-9-30 13:01 , Processed in 0.033360 second(s), 10 queries , Redis On.

Powered by Discuz! X3.4

Copyright © 2001-2021, Tencent Cloud.

快速回复 返回顶部 返回列表