如何使用ExcelReader将数据导入数据库

时间:2018-07-25 14:46:07

标签: c# sql

我正在尝试让我的程序读取.csv文件,然后根据输入的值创建数据库名称,在该数据库中,它应该使用输入的文本创建一个表,然后从该表中获取每个标题。 excel文件,并将其设置为新创建的表中的一列。有人可以帮助我了解我如何去做吗?大部分是关于阅读和创建专栏的最后一部分。以下是我到目前为止拥有的代码,它可能大部分都不完整或没有意义,但是请记住,我对此并不陌生。

public void btnSubmit_Click(object sender, RoutedEventArgs e)
{
    string DataTableName;
    string DataBaseName;
    string ImportPath;

    DataTableName = TxtMappingArea.Text;
    DataBaseName = TxtDistributionCenter.Text;
    ImportPath = TxtCSVFileName.Text;


    String str;
    SqlConnection myConn = new SqlConnection("Server=localhost;Integrated security=true; database=master");

    str = "CREATE DATABASE " + DataBaseName + " ON PRIMARY " +
        "(NAME = " + DataBaseName + ", " +
        "FILENAME = 'D:\\Microsoft SQL Server\\MSSQL14.MSSQLSERVER\\MSSQL\\DATA\\" + DataBaseName + ".mdf'" + ", " +
        "SIZE = 2MB, MAXSIZE = 10MB, FILEGROWTH = 10%) " +
        "LOG ON (NAME = " + DataBaseName + "_Log, " +
        "FILENAME = 'D:\\Microsoft SQL Server\\MSSQL14.MSSQLSERVER\\MSSQL\\DATA\\" + DataBaseName + ".ldf', " +
        "SIZE = 1MB, " +
        "MAXSIZE = 5MB, " +
        "FILEGROWTH = 10%)";

    SqlCommand myCommand = new SqlCommand(str, myConn);
    try
    {
        myConn.Open();
        myCommand.ExecuteNonQuery();
        MessageBox.Show("DataBase is Created Successfully", "MyProgram", MessageBoxButton.OK, MessageBoxImage.Information);
    }
    catch (System.Exception ex)
    {
        MessageBox.Show(ex.ToString(), "MyProgram", MessageBoxButton.OK, MessageBoxImage.Information);
    }
    finally
    {
        if (myConn.State == ConnectionState.Open)
        {
            myConn.Close();
        }
    }

    using (var stream = File.Open(ImportPath, FileMode.Open, FileAccess.Read))
    {
        using (var reader = ExcelReaderFactory.CreateCsvReader(stream))
        {
            var result = reader.AsDataSet();
        }
    }

    String str2;


    ////This is where I am stuck in my code:

    //str2 = "CREATE TABLE " + DataTableName + 

    SqlCommand myCommand2 = new SqlCommand(str2, myConn);
    try
    {
        myConn.Open();
        myCommand.ExecuteNonQuery();
        MessageBox.Show("DataBase is Created Successfully", "MyProgram", MessageBoxButton.OK, MessageBoxImage.Information);
    }
    catch (System.Exception ex)
    {
        MessageBox.Show(ex.ToString(), "MyProgram", MessageBoxButton.OK, MessageBoxImage.Information);
    }
    finally
    {
        if (myConn.State == ConnectionState.Open)
        {
            myConn.Close();
        }
    }
}

0 个答案:

没有答案