【发布时间】:2018-09-26 01:19:14
【问题描述】:
我有大约 20 个文件,全部包含 20 张或更多张。我需要将所有工作表中的特定数据导入表格(与表格相同的列)。我的代码只导入一张纸。如何导入多张工作表?以及如何从 Excel 导入特定单元格?我已经阅读了很多问题,但没有一个能满足我的需求,而且大部分都是旧的
数据库是 SQL Server。我希望你能帮助我。我是新手。
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult Index(HttpPostedFileBase postedFile)
{
string filePath = string.Empty;
if (postedFile != null)
{
string path = Server.MapPath("~/Uploads/");
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
filePath = path + Path.GetFileName(postedFile.FileName);
string extension = Path.GetExtension(postedFile.FileName);
postedFile.SaveAs(filePath);
string conString = string.Empty;
switch (extension)
{
case ".xls": //Excel 97-03.
conString = ConfigurationManager.ConnectionStrings["Excel03ConString"].ConnectionString;
break;
case ".xlsx": //Excel 07 and above.
conString = ConfigurationManager.ConnectionStrings["Excel07ConString"].ConnectionString;
break;
}
DataTable dt = new DataTable();
conString = string.Format(conString, filePath);
using (OleDbConnection connExcel = new OleDbConnection(conString))
{
using (OleDbCommand cmdExcel = new OleDbCommand())
{
using (OleDbDataAdapter odaExcel = new OleDbDataAdapter())
{
cmdExcel.Connection = connExcel;
//Get the name of First Sheet.
connExcel.Open();
DataTable dtExcelSchema;
dtExcelSchema = connExcel.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
string sheetName = dtExcelSchema.Rows[0]["TABLE_NAME"].ToString();
connExcel.Close();
//Read Data from First Sheet.
connExcel.Open();
cmdExcel.CommandText = "SELECT * From [" + sheetName + "]";
odaExcel.SelectCommand = cmdExcel;
odaExcel.Fill(dt);
connExcel.Close();
}
}
}
conString = ConfigurationManager.ConnectionStrings["Constring"].ConnectionString;
using (SqlConnection con = new SqlConnection(conString))
{
using (SqlBulkCopy sqlBulkCopy = new SqlBulkCopy(con))
{
//Set the database table name.
sqlBulkCopy.DestinationTableName = "dbo.Table_1";
//[OPTIONAL]: Map the Excel columns with that of the database table
sqlBulkCopy.ColumnMappings.Add("Rut", "Rut");
sqlBulkCopy.ColumnMappings.Add("Nombres", "Nombres");
sqlBulkCopy.ColumnMappings.Add("Malla", "Malla");
con.Open();
sqlBulkCopy.WriteToServer(dt);
con.Close();
}
}
}
return View();
}
}
【问题讨论】:
-
我的建议是全部导入,然后剔除你不需要的。
-
我同意这一点。并且还可以在手前好好哭泣,因为您将需要它。导入 Excel 文件是最烦人的事情之一,因为 Excel 工作表几乎从来都不一致。人们只是无法自拔。我总是先把它放在一张桌子上,然后再担心一旦我到了那里就解决了。
-
但是知道类、库什么的?
标签: c# sql-server excel asp.net-mvc