Lazarus中文社区

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

QQ登录

只需一步,快速开始

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

使用道具 举报

*滑块验证:

本版积分规则

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

GMT+8, 2025-5-2 22:23 , Processed in 0.028623 second(s), 10 queries , Redis On.

Powered by Discuz! X3.4

Copyright © 2001-2021, Tencent Cloud.

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