Excel导入错误在ASP.net

我想通过数据集从asp.net网站导入一个Excel的数据库。

这是我的第一部分。

int xlColCount = 1; wb = app.Workbooks.Open(FilePath, 0, false, 5, "", "", true, Ex.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0); ws = (Ex.Worksheet)wb.ActiveSheet; xlColCount = ws.Columns.Count; xlColCount = ws.UsedRange.Columns.Count; ws.Columns.ClearFormats(); xlColCount = ws.UsedRange.Columns.Count; //creating datacolumns for (int i = 0; i < xlColCount; i++) { try { DSname.Tables[0].Columns.Add(((Ex.Range)ws.Cells[1,strColArr[i]]).Value2.ToString().Trim()); } catch(Exception ex) { //error occured } } 

首先,我将基于excel标题的列名创build到数据集列中。 这里xlColCount = 198(excel模板中所有列的总数都被填充),但是当到达第172列(i = 172)时,它给出索引超出范围错误。

可能是什么原因? 我需要创build一个包含所有excel列名的列名的数据集。

检查你的strColArr [i]数组的容量。可以初始化为172或更小的大小。

也许你会有更好的结果(和性能)与ADO.NET和System.Data.OleDb

 string filePath = @"C:\Workbook1.xls"; string connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filePath + ";Extended Properties=\"Excel 8.0\";"; OleDbConnection connection = new OleDbConnection(connectionString); string cmdText = "SELECT * FROM [Sheet1$]"; OleDbCommand command = new OleDbCommand(cmdText, connection); command.Connection.Open(); OleDbDataReader reader = command.ExecuteReader(); if (reader.HasRows) { while (reader.Read()) { Console.WriteLine("{0}\t{1}", reader[0].ToString(), reader[1].ToString()); } } 

string filePath =“”:

  OleDbCommand cmd = new OleDbCommand(); ; OleDbDataAdapter oleda = new OleDbDataAdapter(); DataSet ds = new DataSet(); DataTable dt = new DataTable(); UserBase loginUser = (UserBase)Session["LoggedUser"]; SearchFilter filter = new SearchFilter(); string action = "ExportDocumentType"; filter.DocumentTypeID = Convert.ToInt32(cmbDocumentType.SelectedValue); filter.DepartmentID = Convert.ToInt32(cmbDepartment.SelectedValue); try { Logger.Trace("Started Extracting Soft Data", Session["LoggedUserId"].ToString()); // need to pass relative path after deploying on server oledbConn = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filePath + ";Extended Properties='Excel 12.0;';"); try { oledbConn.Open(); } catch { string con = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + filePath + ";" + "Extended Properties=Excel 8.0;HDR=Yes;IMEX=1"; oledbConn = new OleDbConnection(con); oledbConn.Open(); } // Get the data table containg the schema guid. dt = oledbConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null); if (dt == null) { throw new Exception(" No sheets available!"); } String[] excelSheets = new String[dt.Rows.Count]; int i = 0; // Add the sheet name to the string array. foreach (DataRow row in dt.Rows) { excelSheets[i] = row["TABLE_NAME"].ToString(); i++; } cmd.Connection = oledbConn; cmd.CommandType = CommandType.Text; // Get column names of selected document type string SelectCommand = getIndexFieldsList(); SelectCommand = "SELECT " + SelectCommand + " FROM [" + excelSheets[0] + "]"; cmd.CommandText = SelectCommand; oleda = new OleDbDataAdapter(cmd); try { oleda.Fill(ds); } catch { throw new Exception("Selected file is not matching to " + cmbDocumentType.SelectedItem.Text + ".");//Bug Wrtier DMS ENHSMT 1-1012 M } string strXml = string.Empty; if (ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0) { // note: Do ur code here.. i prefer to create a insert satement from here using looping it out } else { throw new Exception(" No data available in uploaded file!");//Bug Wrtier DMS ENHSMT 1-1012 M } } catch (Exception ex) { Logger.Trace("Exception:" + ex.Message, Session["LoggedUserId"].ToString()); throw new Exception(ex.Message.ToString()); } finally { // Clean up. if (oledbConn != null) { oledbConn.Close(); oledbConn.Dispose(); } if (dt != null) { dt.Dispose(); } if (ds != null) { ds.Dispose(); } } }