现在的位置: 首页 > 综合 > 正文

C# 读取Excel表格中的内容

2013年02月27日 ⁄ 综合 ⁄ 共 1187字 ⁄ 字号 评论关闭

using System.Reflection;
using System.Runtime.InteropServices;
using Excel = Microsoft.Office.Interop.Excel;

//操作Excel的变量
            Excel.Application xApp = null;
            Excel.Worksheet xSheet = null;
            Excel.Workbook xBook = null;
            Excel.Range rng2 = null;
//创建Application对象
                xApp = new Excel.ApplicationClass();
                xApp.Visible = false;
                //得到WorkBook对象, 可以用两种方式之一: 下面的是打开已有的文件
                xBook = xApp.Workbooks._Open(m_strFilename,
                Missing.Value, Missing.Value, Missing.Value, Missing.Value
                , Missing.Value, Missing.Value, Missing.Value, Missing.Value
                , Missing.Value, Missing.Value, Missing.Value, Missing.Value);

                //获取第一个表单
                xSheet = (Excel.Worksheet)xBook.Sheets[1];
                //获取列数
                m_nColumn_Count = xSheet.UsedRange.Columns.Count;
                //获取行数
                m_nRow_Count = xSheet.UsedRange.Rows.Count;
//读取,通过Range对象,得到单元格 ,行列都从1开始
                    rng2 = (Excel.Range)xSheet.Cells[i, j];

xSheet = null;
                xBook = null;
                if (null != xApp)
                {
                    xApp.Quit(); //这一句是非常重要的,否则Excel对象不能从内存中退出
                    xApp = null;
                }

【上篇】
【下篇】

抱歉!评论已关闭.