如何使用Microsoft.Office.Interop.Excel读取Excel文件中的特定工作表

时间:2013-05-29 11:05:55

标签: c# excel

我想使用“Microsoft.Office.Interop.Excel”阅读excel文件中的特定工作表。 我的代码就像

    private static Microsoft.Office.Interop.Excel.ApplicationClass appExcel;
    private static Workbook newWorkbook = null;
    private static _Worksheet objsheet = null;

    static void excel_init(String path)
    {
        appExcel = new Microsoft.Office.Interop.Excel.ApplicationClass();

        if (System.IO.File.Exists(path))
        {
                newWorkbook = appExcel.Workbooks.Open(path, true, true);
                objsheet = (_Worksheet)appExcel.ActiveWorkbook.ActiveSheet;               
        }
        else
        {
            MessageBox.Show("Unable to open file!");               
        }
    }

如何更改此内容以阅读特定表格?

2 个答案:

答案 0 :(得分:1)

你应该尝试这种方式:

static void Main(string[] args)
            {
                try
                {

                    OleDbConnection oledbConn;

                    string path = System.IO.Path.GetFullPath(@"D:\FileName.XLS");

                    oledbConn = new OleDbConnection(@"provider=Microsoft.Jet.OLEDB.4.0;Data Source='" +
                            path + "';Extended Properties=Excel 8.0;");

                    oledbConn.Open();
                    OleDbCommand cmd = new OleDbCommand(); ;
                    OleDbDataAdapter oleda = new OleDbDataAdapter();
                    DataSet ds = new DataSet();


                    cmd.Connection = oledbConn;
                    cmd.CommandType = CommandType.Text;
                    cmd.CommandText = "SELECT * FROM [sheet2]";
                    oleda = new OleDbDataAdapter(cmd);
                    oleda.Fill(ds, "dsSlno");
                    oledbConn.Close();

                }
                catch (Exception)
                {

                    throw;
                }

            }

答案 1 :(得分:0)

如下所示

var sheet = (_Worksheet)appExcel.ActiveWorkbook.Sheets["Sheet2"];
sheet.Select(Type.Missing);