从打开的excel文件中导入数据

本文关键字:导入 数据 文件 excel | 更新日期: 2023-09-27 18:10:33

我需要从MS Excel 2010/2013当前打开的文件导入数据到我的c#应用程序。我用的是vs2010 Express,所以不能用Microsoft.Office.Interop.Excel。我尝试使用lib电子表格灯,但我无法解决这个问题。我怎么能做到呢?

从打开的excel文件中导入数据

试试下面的代码:

 OleDbConnection oledbConn = new OleDbConnection();
        try
        {
            string path = HttpContext.Current.Server.MapPath("~/virtual path for your file");
            if (Path.GetExtension(path) == ".xls")
            {
                oledbConn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + path + ";Extended Properties='"Excel 8.0;HDR=Yes;IMEX=2'"");
            }
            else if (Path.GetExtension(path) == ".xlsx")
            {
                oledbConn = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Extended Properties='Excel 12.0;HDR=YES;IMEX=1;';");
            }
            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 [Sheet1$]";
            oleda = new OleDbDataAdapter(cmd);
            oleda.Fill(ds, "your_temp_table_name");
            foreach (DataRow item in ds.Tables["your_temp_table_name"].Rows)
            {
                ....