0

我有下面的代码,允许我将 Excel 表中的数据直接添加到给定的数据库中,现在我想知道如何多次调用该方法以一次从两个不同的 Excel 文件中添加数据,这是一个按钮,一旦单击,就会调用此方法,使用多线程。

private void AddToDatabase()
{
    using (OleDbConnection connection =
                new OleDbConnection(excelConnectionString))
    {
         connection.Open();
         CheckNumeberOfSheets(connection);
    }
}

按钮代码;

private void button1_Click(object sender, EventArgs e)
{
    AddToDatabase();
}
4

2 回答 2

1

可能您可以将字符串传递给您的方法 AddToDatabse ,例如

   private void AddToDatabase(string fileName){
    if(fileName.Equals("yourfirstFile"))
     {
      using (OleDbConnection connection =
            new OleDbConnection(excelConnectionString))
            {
                connection.Open();
                CheckNumeberOfSheets(connection);

            }
      }
    else if(fileName.Equals("yoursecondfile"))
     {
      using (OleDbConnection connection =
            new OleDbConnection(excelConnectionString2))
            {
                connection.Open();
                CheckNumeberOfSheets(connection);

            }
      }
    }

然后这样称呼它

    private void button1_Click(object sender, EventArgs e)
    {
         AddToDatabase("yourfirstFile");
         AddToDatabase("yoursecondFile");
    }
于 2013-05-15T10:48:10.920 回答
0

第 1 步:创建一个名为“ClassFiles”的类

public class ClassFiles
{

private String fileName;
private String excelConnectionString;


public String getFileName()
 return fileName;

public void setFileName(String fileName)
{
 this.fileName=fileName;
}

public String getExcelConnectionString()
 return excelConnectionString;

public void setExcelConnectionString(String excelConnectionString)
{
 this.excelConnectionString=excelConnectionString;
}
}

第 2 步:在您的主类中,添加文件名以及 excelConnection 字符串,例如:

public class MainClass{


private void AddFilesToDB(List<ClassFiles>fileDetails){

  for(ClassFiles fileDeteil : fileDetails){

            using (OleDbConnection connection =
            new OleDbConnection(fileDeteil.getExcelConnectionString))
            {
                connection.Open();
                CheckNumeberOfSheets(connection);

            }

  // as well as u can get the file name..
           String fileName=fileDeteil.getFileName();
    }
}

public Static void main(string args[]){

    List<ClassFiles> addDetails =new ArrayList<ClassFiles>();
    //now add the no of files into the list
     ClassFiles objFile1=new ClassFiles();
     objFile1.setFileName("filename1");
     objFile1.setExcelConnectionString("excelConnectionString1");
     addDetails.add(objFile1);

     ClassFiles objFile2=new ClassFiles();
     objFile2.setFileName("filename2");
     objFile2.setExcelConnectionString("excelConnectionString2");
     addDetails.add(objFile2);

     and so on..
     then call the function for further process.,

    new MainClass().AddFilesToDB(addDetails);
  }

hope it ll help you..

于 2013-05-15T11:42:01.783 回答