delphi讀取excel的兩種方法

兩種方法,一是用ADO連接,問題是Excel文件內容要規則,二是用OLE打開,但操作就沒有象
操作數據庫那麼方便了.

一、用ADO連接:
設置屬性ConnetionString
選擇 Microsoft Jet 4.0 OLE DB provider
Select or enter a datasorce name -> 選擇你要打開Excel文件
User name默認是Admin 密碼默認爲空,可以不用理會
Extended 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;
a.activecell.columnwidth:=10;
showmessage(inttostr(a.activecell.columnwidth));

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章