在.NET中用MICROSOFT的Excel.Application 部件读取Excel表
首先
在.NET的解决方案管理器中右键单击工程找到添加引用,在选项卡里选择COM 在列表里找到Excelxx(xx是版本号有9.0;10.0等,对了一定要先安装Excel啊,否则找不到的),选择确定,然后就可以在你的程序中Excel.ApplicationClass了
string excelFilePath = @"C:\Inetpub\wwwroot\news\test.xls";
Excel.Application myExcel = new Excel.ApplicationClass();
object oMissing = System.Reflection.Missing.Value;
myExcel.Application.Workbooks.Open(excelFilePath, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing);
Excel.Workbook myBook = myExcel.Workbooks[1];
Excel.Worksheet mySheet = (Excel.Worksheet)myBook.Worksheets[1];
System.Data.DataTable dt = new System.Data.DataTable("mytable");
dt.Columns.Add("F1", System.Type.GetType("System.String"));
dt.Columns.Add("F2", System.Type.GetType("System.String"));
dt.Columns.Add("F3", System.Type.GetType("System.String"));
dt.Columns.Add("F4", System.Type.GetType("System.String"));
dt.Columns.Add("F5", System.Type.GetType("System.String"));
DataSet myDs = new DataSet();
myDs.Tables.Add(dt);
DataRow myRow;
myDs.Clear();
for (int i = 2; i <= 4; i++) //第一行为标题,不读取
{
myRow = myDs.Tables["mytable"].NewRow();
for (int j = 1; j <= 5; j++)
{
Excel.Range r = (Excel.Range)mySheet.Cells[i, j];
string strValue = r.Text.ToString();
string aa = strValue;
Response.Write("--"+aa+"--");
// string columnname = "F" + j.ToString();
//myRow[columnname] = strValue;
}
Response.Write("</br>");
//myDs.Tables["mytable"].Rows.Add(myRow);
}
//DataGrid1.DataSource = myDs.Tables["mytable"].DefaultView;
// DataGrid1.DataBind();