原創(chuàng)|其它|編輯:郝浩|2012-10-09 16:23:40.000|閱讀 3126 次
概述:在Delphi中讀取Excel文件,使用CreateOleObject的方式挺討厭的,一直搞不定,輸出了文件之后,總會(huì)在系統(tǒng)中打開一個(gè)Excel,就算Quit也不行,一個(gè)程序中使用的多了,還不定搞出什么事情來(lái)。狠狠心找個(gè)其它的東西來(lái)代替,于是發(fā)現(xiàn)了XlsReadWriteII。
# 界面/圖表報(bào)表/文檔/IDE等千款熱門軟控件火熱銷售中 >>
在Delphi中讀取Excel文件,使用CreateOleObject的方式挺討厭的,一直搞不定,輸出了文件之后,總會(huì)在系統(tǒng)中打開一個(gè)Excel,就算Quit也不行,一個(gè)程序中使用的多了,還不定搞出什么事情來(lái)。狠狠心找個(gè)其它的東西來(lái)代替,于是發(fā)現(xiàn)了XlsReadWriteII。
使用之后發(fā)現(xiàn)這個(gè)東西真不錯(cuò),簡(jiǎn)單好用。不管是讀還是寫均輕松搞定。下面是Demo中的代碼。
寫文件代碼,包括對(duì)格式的定制:
XLS.Filename := 'FormatSample.xls'; XLS.Clear; // Add format #0 with XLS.Formats.Add do begin FontIndex := XLS.Fonts.AddIndex; XLS.Fonts[FontIndex].Name := 'Courier new'; XLS.Fonts[FontIndex].Size := 14; XLS.Fonts[FontIndex].Color := xcRed; end; // Add format #1 with XLS.Formats.Add do begin FontIndex := XLS.Fonts.AddIndex; XLS.Fonts[FontIndex].AssignTFont(Font); end; // Add format #2 with XLS.Formats.Add do begin FillPatternForeColor := xcLilac; end; // Add format #3 with XLS.Formats.Add do begin BorderTopColor := xcBlue; BorderBottomColor := xcBlue; BorderTopStyle := cbsThin; BorderBottomStyle := cbsThick; end; // Add format #4 // ShortDateFormat is a Delphi global variable for the local date format. with XLS.Formats.Add do begin NumberFormat := ShortDateFormat; end; XLS.Sheets[0].WriteString(1,2,0,'Format #0'); XLS.Sheets[0].WriteString(1,3,1,'Format #1'); XLS.Sheets[0].WriteString(1,4,2,'Format #2'); XLS.Sheets[0].WriteString(1,5,3,'Format #3'); XLS.Sheets[0].WriteNumber(1,6,4,Date); XLS.Write; //如果需要另存為一個(gè)文件,改FileName之后再寫一次,如需更改工作簿的名稱,設(shè)置Sheets[0].Name就可以了。
讀取文件代碼:
var Col,Row: integer; Sum: double; begin if edFilename.Text = '' then begin ShowMessage('Filename is missing'); Exit; end; Sum := 0; XLS.Filename := edFilename.Text; XLS.Read; //此行不能省,否則讀取不到數(shù)據(jù) XLS.Sheets[0].LastCol := 255; XLS.Sheets[0].LastRow := 65535; for Col := XLS.Sheets[0].FirstCol to XLS.Sheets[0].LastCol do begin for Row := XLS.Sheets[0].FirstRow to XLS.Sheets[0].LastRow do begin if (Row < Grid.RowCount) and (Col < Grid.ColCount) then Grid.Cells[Col + 1,Row + 1] := XLS.Sheets[0].AsFmtString[Col,Row]; if XLS.Sheets[0].CellType[Col,Row] = ctFloat then Sum := Sum + XLS.Sheets[0].AsFloat[Col,Row]; end; end; lblSum.Caption := Format('The sum of all numeric cells are: %.2f',[Sum]); Grid.Invalidate; end;
本站文章除注明轉(zhuǎn)載外,均為本站原創(chuàng)或翻譯。歡迎任何形式的轉(zhuǎn)載,但請(qǐng)務(wù)必注明出處、不得修改原文相關(guān)鏈接,如果存在內(nèi)容上的異議請(qǐng)郵件反饋至chenjj@fc6vip.cn
文章轉(zhuǎn)載自:龍少爺?shù)牟┛?博客園