是否可以不指定工作表名称和列?

时间:2019-05-09 12:06:34

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

所以,我正在做一个程序,它将一个excel文件导入到sql数据库,如果我指定excel的列和数据库列以及工作表名称,一切都可以正常工作。我将详细说明问题所在:

protected void Upload_Click(object sender, EventArgs e)
{
    string excelPath = Server.MapPath("~/Nova pasta/") + Path.GetFileName(FileUpload1.PostedFile.FileName);

    string filepath = Server.MapPath("~/Nova pasta/") + Path.GetFileName(FileUpload1.FileName);
    string filename = Path.GetFileName(filepath);
    FileUpload1.SaveAs(excelPath);
    string ext = Path.GetExtension(filename);

    String strConnection = @"Data Source=PEDRO-PC\SQLEXPRESS;Initial Catalog=costumizado;Persist Security Info=True;User ID=sa;Password=1234";
    string excelConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filepath + ";Extended Properties=\"Excel 12.0 Xml;HRD=YES;IMEX=1;\"";

    OleDbConnection excelConnection = new OleDbConnection(excelConnectionString);

    OleDbCommand cmd = new OleDbCommand("Select * from [rptListaMovs_4$]", excelConnection);

    excelConnection.Open();

    cmd.ExecuteNonQuery();

    DataSet ds = new DataSet();

    SqlDataAdapter da = new SqlDataAdapter("Select * from [rptListaMovs_4$] ", strConnection);

    OleDbDataReader dReader;
    dReader = cmd.ExecuteReader();

    using (SqlBulkCopy sqlBulk = new SqlBulkCopy(strConnection))
    {
        sqlBulk.DestinationTableName = "Dados";
        sqlBulk.ColumnMappings.Add("Data Mov", "Data Mov.");
        sqlBulk.ColumnMappings.Add("Data Valor", "Data Valor");
        sqlBulk.ColumnMappings.Add("Descrição do Movimento", "Descrição do Movimento");
        sqlBulk.ColumnMappings.Add("Valor em EUR", "Valor em EUR");

        sqlBulk.WriteToServer(dReader);
    }

    excelConnection.Close();
}

为此:"Select * from [rptListaMovs_4$]"

我想要这个:"Select * from ["+SheetNameWithoutCopyPastHisName+"]"

对此有兴趣

sqlBulk.ColumnMappings.Add("Data Mov", "Data Mov.");
sqlBulk.ColumnMappings.Add("Data Valor", "Data Valor");
sqlBulk.ColumnMappings.Add("Descrição do Movimento", "Descrição do Movimento");
sqlBulk.ColumnMappings.Add("Valor em EUR", "Valor em EUR");

我想要一些东西,不必放入列名,因为有时我想导入具有不同架构的excel,但不允许我这样做

1 个答案:

答案 0 :(得分:2)

您应该可以使用以下方法获取工作表的第一名称:

DataTable schema = excelConnection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
string sheetName = schema.Rows[0]["TABLE_NAME"].ToString();

对于字段名称,这应该可以解决问题:

for(int i = 0; i < dReader.FieldCount; i++)
{
    sqlBulk.ColumnMappings.Add(dReader.GetName(i), dReader.GetName(i));
}