總是感覺對於c#中讀取excel檔案是非常麻煩,還是決定自己來封裝乙個基於com介面的類解決這個問題。
整體設計以及實現如下(首先**入對於microsoft.csharp以及office object library、excel object library 譬如12.0版本的引用):
public
sealed
class
excelfilereader
private
string
m_strfilename =
null
;private
null
;private
workbook
m_workbook =
null
;private
intm_totalsheets = 0;
private
intm_activesheet = 0;
private
intm_sheetcolumns = 0;
private
intm_sheetrows = 0;
public
excelfilereader(
string
filename)
m_strfilename = filename;
public
string
filename
getset
public
inttotalsheets
getpublic
intactivesheetindex
getpublic
intsheetcolumns
getpublic
intsheetrows
getpublic
void
this
new();
try
this
this
.m_strfilename,
type
.missing,
type
.missing,
type
.missing,
type
.missing,
type
.missing,
type
.missing,
type
.missing,
type
.missing,
type
.missing,
type
.missing,
type
.missing,
type
.missing,
type
.missing,
type
.missing);
this
.m_totalsheets =
this
.m_workbook.sheets.count;
catch
public
void
scanexcelsheetsizebyindex(
intsheetindex)
worksheet
sheet = (
worksheet
)m_workbook.sheets[sheetindex];
range
excelrange = sheet.usedrange;
this
.m_sheetcolumns = excelrange.columns.count;
this
.m_sheetrows = excelrange.rows.count;
this
.m_activesheet = sheetindex;
public
void
scanexcelsheetsizebyname(
string
strname)
for(
intsheetnumber = 1; sheetnumber < m_totalsheets + 1; sheetnumber++)
worksheet
sheet = (
worksheet
)m_workbook.sheets[sheetnumber];
if(sheet.name.tolower().equals(strname.tolower()))
this
.m_activesheet = sheetnumber;
range
excelrange = sheet.usedrange;
this
.m_sheetcolumns = excelrange.columns.count;
this
.m_sheetrows = excelrange.rows.count;
public
string
getcellvalue(
introw,
intcolumn)
worksheet
sheet = (
worksheet
)m_workbook.sheets[
this
.m_activesheet];
string
cellinfo = ((excel.
range
)sheet.cells[row, column]).value;
return
cellinfo;
public
void
try
this
.m_workbook.close(
false
, this
.m_strfilename,
null
);marshal
.releasecomobject(
this
.m_workbook);
catch
使用測試的方法,這裡以乙個路由整個excel檔案的所有格仔內容為例來設計使用案例:
static
void
main(
string
args)
excelfilereader
efr =
newexcelfilereader
(@"d:\work\cimc\parser\test.xlsx"
);int
sheets = efr.totalsheets;
for(
inti = 1; i <= sheets; i++)
efr.scanexcelsheetsizebyindex(i);
introws = efr.sheetrows;
intcolumns = efr.sheetcolumns;
for(
intm=1; m<=rows; m++)
for(
intn=1; n<=columns; n++)
string
strvalue = efr.getcellvalue(m, n);
console
.writeline(strvalue);
讀取excel,類封裝(4)
基礎用例資料類 class caseinfo def init self,case id,case name,case module,case pri,case step,case result self.case id case id self.case name case name self.c...
C 讀取配置檔案的封裝類config
c 中讀取配置檔案的類封裝,很好用,直接可以用 config.h pragma once include include include include include brief generic configuration class class config std string getcomm...
讀取Excel檔案中的資料
string strsource file1.value string connstr provider microsoft.jet.oledb.4.0 data source strsource extended properties excel 8.0 string query select f...