我在mvc5中从xls文件上传excel我有以下方法
public ActionResult Importexcel()
{
if (Request.Files["FileUpload1"].ContentLength > 0)
{
string fileExtension =
System.IO.Path.GetExtension(Request.Files["FileUpload1"].FileName);
if (fileExtension == ".xls" || fileExtension == ".xlsx")
{
// Create a folder in App_Data named ExcelFiles because you need to save the file temporarily location and getting data from there.
string path1 = string.Format("{0}/{1}", Server.MapPath("~/Content/UploadedFolder"), Request.Files["FileUpload1"].FileName);
if (System.IO.File.Exists(path1))
System.IO.File.Delete(path1);
Request.Files["FileUpload1"].SaveAs(path1);
string sqlConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path1 + ";Extended Properties=Excel 12.0;Persist Security Info=False";
//Create Connection to Excel work book and add oledb namespace
OleDbConnection excelConnection = new OleDbConnection(sqlConnectionString);
excelConnection.Open();
DataTable dt = new DataTable();
dt = excelConnection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
if (dt == null)
{
return null;
}
String[] excelSheets = new String[dt.Rows.Count];
int t = 0;
//excel data saves in temp file here.
foreach (DataRow row in dt.Rows)
{
excelSheets[t] = row["TABLE_NAME"].ToString();
t++;
}
OleDbConnection excelConnection1 = new OleDbConnection(sqlConnectionString);
DataSet ds = new DataSet();
string query = string.Format("Select * from [{0}]", excelSheets[0]);
using (OleDbDataAdapter dataAdapter = new OleDbDataAdapter(query, excelConnection1))
{
dataAdapter.Fill(ds);
}
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
SqlConnection sqlc = new SqlConnection();
sqlc.ConnectionString = @"Data Source=(LocalDb)\v11.0;AttachDbFilename=|DataDirectory|\aspnet-Planetskool-20140309125429.mdf;Initial Catalog=aspnet-Planetskool-20140309125429;Integrated Security=True";
SqlCommand cmd2 = new SqlCommand("INSERT INTO UserInfo (UserInfoID, GraphID, UserCreatorId,UserLevelEnumId,Birthdate,Zipcode,UserLevel,UserID) VALUES(@UserInfoID, @GraphID, @UserCreatorId,@UserLevelEnumId,@Birthdate,@Zipcode,@UserLevel,@UserID)", sqlc);//@OB_ID is indentity primary key
cmd2.Parameters.Add("@UserInfoID", SqlDbType.UniqueIdentifier).Value = Guid.Parse(ds.Tables[0].Rows[i]["UserInfoID"].ToString());
cmd2.Parameters.Add("@GraphID", SqlDbType.UniqueIdentifier).Value = Guid.Parse(ds.Tables[0].Rows[i]["GraphID"].ToString());
cmd2.Parameters.Add("@UserCreatorId", SqlDbType.UniqueIdentifier).Value = Guid.Parse(ds.Tables[0].Rows[i]["UserCreatorId"].ToString());
cmd2.Parameters.Add("@UserLevelEnumId", SqlDbType.UniqueIdentifier).Value = Guid.Parse(ds.Tables[0].Rows[i]["UserLevelEnumId"].ToString());
// cmd2.Parameters.Add("@Birthdate", SqlDbType.DateTime).Value = DateTime.UtcNow.ToLocalTime();
cmd2.Parameters.Add("@Zipcode", SqlDbType.NVarChar).Value = (ds.Tables[0].Rows[i]["Zipcode"].ToString());
cmd2.Parameters.Add("@UserLevel", SqlDbType.NVarChar).Value = (ds.Tables[0].Rows[i]["Zipcode"].ToString());
cmd2.Parameters.Add("@UserID", SqlDbType.UniqueIdentifier).Value = Guid.Parse(ds.Tables[0].Rows[i]["UserID"].ToString());
sqlc.Open();
cmd2.ExecuteNonQuery();
sqlc.Close();
//db.StudentRecords.Add(model);
//db.SaveChanges();
}
return RedirectToAction("Index");
}
}
当我上传文件时,我在我的数据库中只获得了1行我已经调试了visual studio中的行计数我正在调整总行但是无法在我的数据库中获取它
答案 0 :(得分:0)
使用Microsoft.Office.Interop.Excel您可能如下所示......它可能对您有所帮助
public void ImportXLX()
{
Microsoft.Office.Interop.Excel.Application app = new Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel.Workbook wb = app.Workbooks.Open(@"C:\Users\Vipin\Desktop\Sheets\MyXL6.xlsx", Type.Missing, Type.Missing, Type.Missing, Type.Missing,
Type.Missing, Type.Missing, Type.Missing, Type.Missing,
Type.Missing, Type.Missing, Type.Missing, Type.Missing,
Type.Missing, Type.Missing);
int workSheetCounts = wb.Worksheets.Count;
for (int sheetCounter = 1; sheetCounter <= workSheetCounts; sheetCounter++)
{
Microsoft.Office.Interop.Excel.Worksheet workSheet = wb.Sheets[sheetCounter];
Range excelRange = workSheet.UsedRange;
Range objRange = null;
int rowCountForHeight = 0;
double totalColHeight = 0;
double totalRowWidth = 0;
foreach (Microsoft.Office.Interop.Excel.Range row in excelRange.Rows)
{
rowCountForHeight++;
int colCount = 0;
foreach (Microsoft.Office.Interop.Excel.Range c in row.Cells)
{
colCount++;
objRange = workSheet.Cells[rowCountForHeight, colCount];
double height = 0;
if (objRange.MergeCells)
{
Debug.Write("CellsMerged \n");
height = ((Range)objRange.MergeArea[1, 1]).Height;
}
else
{
Debug.Write("CellsMergedNot \n");
height = objRange.Height;
}
totalColHeight = totalColHeight + height;
}
}
int rowCount = 0;
foreach (Microsoft.Office.Interop.Excel.Range row in excelRange.Rows)
{
rowCount++;
totalRowWidth = row.Width;
int colCount = 0;
foreach (Microsoft.Office.Interop.Excel.Range c in row.Cells)
{
colCount++;
objRange = workSheet.Cells[rowCount, colCount];
double width = 0;
double height = 0;
string colVal = null;
if (objRange.MergeCells)
{
colVal = Convert.ToString(((Range)objRange.MergeArea[1, 1]).Text).Trim();
width = objRange.MergeArea.Width;
height = objRange.MergeArea.Height;
}
else
{
colVal = Convert.ToString(objRange.Text).Trim();
width = objRange.Width;
height = objRange.Height;
}
Debug.Write("objRange = " + objRange + " rowCount = " + rowCount + " Width = " + width + " height = " + height + "TotalColumnWidth = " + totalRowWidth + "TotalRowHeight = " + totalColHeight + " \n ");
}
}
}
app.Quit();
}