[英]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.