博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

C#怎样用excel.dll读取excel文件

Posted on 2010-04-19 22:36  moss_tan_jun  阅读(3106)  评论(1编辑  收藏  举报

 

------------

 

  public DataTable ReadExcelToTable(string filepath)
        {
            string excelfilePath = Server.MapPath("Excel/Excel.xls");
            Excel.Application myExcel = new Excel.ApplicationClass();
            Excel.Workbooks myBooks = myExcel.Application.Workbooks;
            object oMissing = System.Reflection.Missing.Value;

            Excel.Workbook myBook = myBooks.Open(excelfilePath, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing);

            //Excel.Workbook myBook = myExcel.Workbooks[1];
            int sheetint = myBook.Worksheets.Count;//能得到sheet的数量

            Excel.Worksheet mySheet = (Excel.Worksheet)myBook.Worksheets[1];
            int rowsint = mySheet.UsedRange.Cells.Rows.Count; //得到行数
            int columnsint = mySheet.UsedRange.Cells.Columns.Count;//得到列数
            System.Data.DataTable dt = new System.Data.DataTable("mytable");
            for (int i = 1; i < columnsint; i++)
            {
                dt.Columns.Add("F" + i.ToString(), System.Type.GetType("System.String"));
            }
            DataSet myDs = new DataSet();
            myDs.Tables.Add(dt);
            DataRow myRow;
            myDs.Clear();

            for (int i = 2; i < rowsint; i++) //第一行为标题,不读取
            {
                myRow = myDs.Tables["mytable"].NewRow();
                for (int j = 1; j < columnsint; j++)
                {

                    Excel.Range r = (Excel.Range)mySheet.Cells[i, j];
                    string strValue = r.Text.ToString();
                    string aa = strValue;
                    string columnname = "F" + j.ToString();
                    myRow[columnname] = strValue;

                }
                myDs.Tables["mytable"].Rows.Add(myRow);
            }

            return myDs.Tables["mytable"];
        }

------------------------

http://www.cnblogs.com/loverjohni/articles/1505783.html

 

-------------------------------

http://cache.baidu.com/c?m=9f65cb4a8c8507ed4fece763104080224e0add216b97c71508d39019d5394c413037bee43a715042cec57e650aad4c41e9f13d773d0937b7ec92ce15c9fecf6879877623701d914062c46fa9dc3222d656934d9da40ee6cae74492b9a3d2c855239d19542ddee78a2a1714bd78f16467bdf88e49654860befa4166e8287d3eec2057b737aeaa63395996f7ad4b3db43da16706e7de22c449&p=c471da16d9c35aec07bd9b780657&user=baidu