如何将xls文件或文本文件中存在的数据转储到C#中的数据库 [英] How to dump data present in xls file or text file to database in c#

查看:85
本文介绍了如何将xls文件或文本文件中存在的数据转储到C#中的数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有一些记录的xls文件和文本文件.

我需要在数据库中插入值.

请帮助我如何将文件中的记录插入数据库.

I have a xls file and text file with some records.

I need to insert values in to database.

Please help me how to insert records from files to database.

推荐答案

您可以使用以下方法将xls数据插入数据库.

You can use the below approach for inserting xls data into database.

if (openFileDialog.ShowDialog(this) == DialogResult.OK)
  {
      path = openFileDialog.InitialDirectory + openFileDialog.FileName;
  }
  string constring = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=" + path + "; Extended Properties=Excel 12.0 Xml";
  OleDbConnection con = new OleDbConnection(constring);
  try
  {
      con.Open();
      dt = con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
      String[] excelSheets = new String[dt.Rows.Count];
      i = 0;
      foreach (DataRow row in dt.Rows)
      {
          excelSheets[i] = row["TABLE_NAME"].ToString();
          i++;
      }

      for (int j = 0; j < excelSheets.Length; j++)
      {
          string query = "SELECT * FROM [" +excelSheets[j]+ "]; ";
          OleDbDataAdapter adp = new OleDbDataAdapter(query, constring);

          DataSet ds = new DataSet();
          string hCode = string.Empty;
          string description = string.Empty;
          adp.Fill(ds);

          foreach (DataRow dr in ds.Tables[0].Rows)
          {
              hCode = Convert.ToString(dr[1]);
              description = Convert.ToString(dr[2]);
              if (!(string.IsNullOrEmpty(hCode) && string.IsNullOrEmpty(description)))
              {

                  dboject.InsertSiteNameIntoDatabase(hCode, description);

              }
          }


      }
      lblDisplay.Text = "Inserted successfully";

  }
  catch (Exception ex)
  {
      dboject.VMSLog(ex.Message);

  }
  finally
  {
      con.Close();

  }


这篇关于如何将xls文件或文本文件中存在的数据转储到C#中的数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆