0

我想使用"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!");               
        }
    }

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

4

2 回答 2

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;
                }

            }
于 2013-05-29T11:18:24.180 回答
0

像下面

var sheet = (_Worksheet)appExcel.ActiveWorkbook.Sheets["Sheet2"];
sheet.Select(Type.Missing);
于 2013-05-29T11:15:15.027 回答