如何将Excel文件导入到数据库ADO.net

时间:2017-08-15 12:23:13

标签: c# sql-server excel ado.net

我尝试使用C#和ADO.net编写代码将Excel文件导入数据库我终于得到了运行代码,但输出错误。

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);
            }
        }
    }
}

但是有一个问题是代码运行没有任何错误,但数据库中的数据不正确,我无法弄清楚出了什么问题。

1 个答案:

答案 0 :(得分:1)

您需要在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)
}

否则,实体框架并不知道您希望将它们插入数据库。