[英]How to import Excel file to Database ADO.net
I tried to write code to import an Excel file to a database using C# and ADO.net I finally got the code to run but the output is wrong.
using Excel;
using System.IO;
namespace ExpPerson
{
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
private void btnImport_Click(object sender, EventArgs e)
{
try
{
OpenFileDialog op = new OpenFileDialog();
op.Filter = "Excel Workbook| *.xls;*.xlsx;*.xlsm";
if (op.ShowDialog() == DialogResult.Cancel)
return;
FileStream stream = new FileStream(op.FileName, FileMode.Open);
IExcelDataReader excelreader = ExcelReaderFactory.CreateOpenXmlReader(stream);
DataSet result = excelreader.AsDataSet();
MaamoonKhalidIssueEntities db = new MaamoonKhalidIssueEntities();
foreach (DataTable table in result.Tables)
{
foreach (DataRow dr in table.Rows)
{
Person addtable = new Person()
{
nname = Convert.ToString(dr[0]),
ncode = Convert.ToString(dr[1]),
nTel1 = Convert.ToString(dr[2]),
nTel2 = Convert.ToString(dr[3]),
nFax = Convert.ToString(dr[4]),
nEmail = Convert.ToString(dr[5]),
nAdd = Convert.ToString(dr[6])
};
}
}
db.SaveChanges();
excelreader.Close();
stream.Close();
MessageBox.Show("Import Sucess","Good",MessageBoxButtons.OK,MessageBoxIcon.Hand);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}
但是有一个问题是代码运行没有任何错误,但数据库中的数据不正确,我无法弄清楚什么是错误的。
您需要调用db.People.Add(addtable);
在DataRow
循环的每次迭代中。
所以:
foreach (DataRow dr in table.Rows)
{
Person addtable = new Person()
{
nname = Convert.ToString(dr[0]),
ncode = Convert.ToString(dr[1]),
nTel1 = Convert.ToString(dr[2]),
nTel2 = Convert.ToString(dr[3]),
nFax = Convert.ToString(dr[4]),
nEmail = Convert.ToString(dr[5]),
nAdd = Convert.ToString(dr[6])
};
db.People.Add(addtable)
}
否则,Entity Framework 不知道您希望将它们插入到数据库中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.