给定的列映射与源或目标中的任何列都不匹配,以获取大量数据



>我在绑定网格上收到错误

string path = string.Concat(Server.MapPath("~/UploadFile/" + FileUpload1.FileName));
FileUpload1.SaveAs(path); 
string excelCS = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=Excel 8.0", path);
using (OleDbConnection con = new OleDbConnection(excelCS))
{
OleDbCommand cmd = new OleDbCommand("select * from [Sheet1$]", con);
con.Open();
DataTable dt = new DataTable();
dt.Load(cmd.ExecuteReader());
// Create DbDataReader to Data Worksheet
DbDataReader dr = cmd.ExecuteReader();
// SQL Server Connection String
string CS = ConfigurationManager.ConnectionStrings["con"].ConnectionString;
SqlBulkCopy bulkInsert = new SqlBulkCopy(CS);
bulkInsert.DestinationTableName = "tbl_data";
for (int i = 0; i < dt.Columns.Count; i++)
{
bulkInsert.ColumnMappings.Add(i, i);
}
bulkInsert.WriteToServer(dr);
BindGridView();
con.Close();
lblerror.Text = "Your file uploaded successfull"

编辑:

private void BindGridView() 
{ 
string conString = 
ConfigurationManager.ConnectionStrings["con"].ConnectionString; 
SqlConnection con = new SqlConnection(conString); 
SqlCommand cmd = new SqlCommand("select * from tbl_data", con); 
con.Open(); 
gvUpload.DataSource = cmd.ExecuteReader(); 
gvUpload.DataBind(); 
con.Close(); 
}

好的,尼茨。这是使用您的代码库可以执行的操作的示例。请在适应您的具体情况后尝试一下。你已经检查过这个问题了吧?

static void Main(string[] args)
{
string path = string.Concat(Server.MapPath("~/UploadFile/" + FileUpload1.FileName));
FileUpload1.SaveAs(path);
string excelCS = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=Excel 8.0", path);
using (OleDbConnection con = new OleDbConnection(excelCS))
{
DataTable excelData = new DataTable();
using (OleDbCommand excelSource = new OleDbCommand("select * from [Sheet1$]", con))
{
con.Open();
excelData.Load(excelSource.ExecuteReader());
}
// SQL Server Connection String
string CS = ConfigurationManager.ConnectionStrings["con"].ConnectionString;
SqlBulkCopy bulkInsert = new SqlBulkCopy(CS);
bulkInsert.DestinationTableName = "tbl_data";   
bulkInsert.ColumnMappings.Add(0,0);
bulkInsert.ColumnMappings.Add(1,1);     
try
{
bulkInsert.WriteToServer(excelData);
}
catch (Exception e)
{
Console.WriteLine(e);
throw;
}
con.Close();
lblerror.Text = "Your file uploaded successfully";
}
BindGridView();
}
private static void BindGridView()
{
string conString = ConfigurationManager.ConnectionStrings["con"].ConnectionString;
using (SqlConnection con = new SqlConnection(conString))
{
using (SqlCommand cmd = new SqlCommand("select ID, Mail_ID from tbl_data", con))
{
con.Open();
var sqlReader = cmd.ExecuteReader();
Console.WriteLine("START: Sql Columns");
foreach (var sqlColumnName in Enumerable.Range(0, sqlReader.FieldCount).Select(sqlReader.GetName))
{
Console.WriteLine(sqlColumnName);
}
Console.WriteLine("END: Sql Columns");
gvUpload.DataSource = sqlReader;
gvUpload.DataBind();
}
}
}

相关内容

  • 没有找到相关文章

最新更新