1.通过excel 8.0的类,期间需要安装O2003PIA.EXE来安装一个发布包
程序如下:
Excel.Application excelApp
=
new
Excel.ApplicationClass();
if (excelApp == null )
... {
MessageBox.Show("无法创建Excel对象,可能您的机器未安装Excel");
return;
}
else
... {
Excel.Workbooks workbooks =excelApp.Workbooks;
Excel._Workbook workbook = workbooks.Add(this.txtFileName.Text.ToString());
Excel.Sheets sheets = workbook.Worksheets;
Excel._Worksheet worksheet = (Excel._Worksheet)sheets.get_Item(1);
if (worksheet == null)
MessageBox.Show("工作表有问题");
string column = worksheet.Columns["A", "1"].ToString();
}
if (excelApp == null )
... {
MessageBox.Show("无法创建Excel对象,可能您的机器未安装Excel");
return;
}
else
... {
Excel.Workbooks workbooks =excelApp.Workbooks;
Excel._Workbook workbook = workbooks.Add(this.txtFileName.Text.ToString());
Excel.Sheets sheets = workbook.Worksheets;
Excel._Worksheet worksheet = (Excel._Worksheet)sheets.get_Item(1);
if (worksheet == null)
MessageBox.Show("工作表有问题");
string column = worksheet.Columns["A", "1"].ToString();
}
2.使用连接字符串
string
Path
=
this
.txtFileName.Text.ToString();
DataSet ds = null ;
string strall = null ;
try
... {
string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + Path + ";" + "Extended Properties=Excel 8.0;";
OleDbConnection conn = new OleDbConnection(strConn);
conn.Open();
string strExcel = "";
OleDbDataAdapter myCommand = null;
strExcel = "select * from [Sheet1$]";
myCommand = new OleDbDataAdapter(strExcel, strConn);
ds = new DataSet();
myCommand.Fill(ds);
for (int i=0; i < ds.Tables[0].Rows.Count; i++)
...{
DataRow newdatarow = ds.Tables[0].Rows[i];
strall = strall + newdatarow.ItemArray[0].ToString() + ",";
}
}
catch (Exception ex)
... {
throw new Exception(ex.Message);
}
userAccount = strall.Substring( 0 , strall.LastIndexOf( " , " ));
DataSet ds = null ;
string strall = null ;
try
... {
string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + Path + ";" + "Extended Properties=Excel 8.0;";
OleDbConnection conn = new OleDbConnection(strConn);
conn.Open();
string strExcel = "";
OleDbDataAdapter myCommand = null;
strExcel = "select * from [Sheet1$]";
myCommand = new OleDbDataAdapter(strExcel, strConn);
ds = new DataSet();
myCommand.Fill(ds);
for (int i=0; i < ds.Tables[0].Rows.Count; i++)
...{
DataRow newdatarow = ds.Tables[0].Rows[i];
strall = strall + newdatarow.ItemArray[0].ToString() + ",";
}
}
catch (Exception ex)
... {
throw new Exception(ex.Message);
}
userAccount = strall.Substring( 0 , strall.LastIndexOf( " , " ));