从打开的Excel文件导入数据

时间:2014-06-28 00:09:10

标签: c# excel

我需要使用MS Excel 2010/2013从已打开的文件中将数据导入到我的C#应用​​程序中。我使用VS 2010 Express,因此无法使用Microsoft.Office.Interop.Excel。我尝试使用lib Spreadsheetlight,但我无法解决这个问题。我怎么能这样做?

1 个答案:

答案 0 :(得分:0)

试试这段代码:

 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)
            {
                ....