delphi读取excel两种⽅法
两种⽅法,⼀是⽤ADO连接,问题是Excel⽂件内容要规则,⼆是⽤OLE打开,但操作就没有象
操作数据库那么⽅便了.
⼀、⽤ADO连接:
设置属性ConnetionString
选择 Microsoft Jet 4.0 OLE DB provider
Select or enter a datasorce name -> 选择你要打开Excel⽂件
User name默认是Admin 密码默认为空,可以不⽤理会
delphi appExtended properties 设为:Excel 8.0
sql语句 select * from [yourtablename] (注意要有[])
⼆、⽤OLE打开(以下是⼀个范例,注释掉的代码也是有⽤的语句,注意要uses ExtCtrls,ComObj单元):
var ExcelApp:Variant;
begin
ExcelApp:=CreateOleObject('Excel.Application');
//ExcelApp.visible:=true;
ExcelApp.Caption:='应⽤程序调⽤ Microsoft Excel';
ExcelApp.WorkBooks.Add; //新增⼯作簿
//ExcelApp.workBooks.Open('C:\My Documents\Ca09lin1.xls'); //打开已存在⼯作簿
ExcelApp.Worksheets[2].activate; //打开第2个⼯作表
//ExcelApp.WorkSheets['第四章'].activate; //打开名为第四章的⼯作表
ExcelApp.Cells[1,4].Value:='第⼀⾏第四列';
ExcelApp.Cells[1,5].Value:='第⼀⾏第五列';
ExcelApp.ActiveSheet.Columns[4].ColumnWidth:=15;
ExcelApp.ActiveSheet.Rows[1].RowHeight:=15;
//ExcelApp.WorkSheets[1].Rows[8].PageBreak:=1; //设置分页符,但似⽆效
//Excelapp.ActiveSheet.Rows[8].PageBreak:=1; //同上
ExcelApp.ActiveSheet.Range['B3:D4'].Borders[2].Weight:=3;
ExcelApp.ActiveSheet.Range['B3:D4'].Borders[1].Weight:=3;
ExcelApp.ActiveSheet.Range['B3:D4'].Borders[3].Weight:=3;
ExcelApp.ActiveSheet.Range['B3:D4'].Borders[4].Weight:=3;
//ExcelApp.ActiveSheet.Range['B3:D4'].Borders[5].Weight:=3; //会直接在范围内的各Cell内加上斜杠|
//ExcelApp.ActiveSheet.Range['B3:D4'].Borders[6].Weight:=3; //与上句类似
//Bordrs:1-左 2-右 3-顶 4-底 5-斜( \ ) 6-斜( / )
ExcelApp.Cells[3,2].Value:='三⾏⼆列';
ExcelApp.Cells[3,3].Value:='三⾏三列';
ExcelApp.Cells[3,4].Value:='三⾏四列';
ExcelApp.Cells[4,2].Value:='四⾏⼆列';
ExcelApp.Cells[4,3].Value:='四⾏三列';
ExcelApp.Cells[4,4].Value:='四⾏四列';
//ExcelApp.ActiveSheet.Range['B3:D4'].Value.CopyToClipBoard;
ExcelApp.activeSheet.Cells[1,4].ClearContents; //清除⼀⾏四列的内容,activeSheet可以省略
Excelapp.Rows[3].font.Name:='⾪书'; //这⾥Rows前省略了activeSheet,但针对也只是当前⼯作表⽽⾮整个⼯作簿ExcelApp.Rows[3].font.Color:=clBlue;
ExcelApp.Rows[3].Font.Bold:=True;
ExcelApp.Rows[3].Font.UnderLine:=True;
ExcelApp.Range['B3:D4'].Copy;
RichEdit1.PasteFromClipboard;
//ExcelApp.ActiveSheet.PageSetup.CenterFooter:='第$P页';
//所有页⾯设置(PageSetup的属性)都不能进⾏,不知为何
//ExcelApp.ActiveSheet.PrintPreview; //打印预览
//ExcelApp.ActiveSheet.PrintOut; //直接打印输出
//if not ExcelApp.ActiveWorkBook.Saved then //⼯作表保存:
// ExcelApp.ActiveSheet.PrintPreview;
//ExcelApp.SaveAs( 'C:\Excel\Demo1.xls' ); //⼯作表另存为
ExcelApp.ActiveWorkBook.Saved := True; // 放弃存盘
ExcelApp.WorkBooks.Close; //关闭⼯作簿
ExcelApp.Quit; //退出 Excel
ExcelApp:=Unassigned;//释放excel进程
end;
另:
得到excel的⾏数、列数:
Maxc :=ExlApp.WorkSheets[1].UsedRange.Columns.Count;
Maxr :=ExlApp.WorkSheets[1].UsedRange.Rows.Count;
得到列宽
a:=createoleobject('excel.application');
a.workbooks.add;
lumnwidth:=10; showmessage(inttostr(lumnwidth));

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。