无法使用C#将Excel上传数据输入到SQL Server数据库中

时间:2018-06-24 14:25:44

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

我正在尝试创建一个函数以选择要上载的文件类型,然后将Excel文件数据上载到SQL Server数据库中。当前,上传功能正在起作用,因为文件已保存到tempfile路径中。但是,即使上传的文件中包含数据,输入数据库表的数据也全部显示为NULL。

我不太确定是什么原因导致的,因为没有错误,所以我想对我做错的事情以及我的代码是否朝着正确的方向提出一些意见。

<div class="form-group form-inline">
<label id="lbl_report" for=" report_upload" style="font-family:Calibri; 
    position:fixed;" >Report : </label>
<br/>
<div class="form-group">
    <asp:DropDownList ID="report_upload" runat="server" AutoPostBack="true" 
        CssClass="form-control">
        <asp:ListItem></asp:ListItem>
        <asp:ListItem Text="Choice 1" Value="val1"></asp:ListItem>
        <asp:ListItem Text=" Choice 2" Value="val2"></asp:ListItem>
        <asp:ListItem Text=" Choice 3" Value="val3"></asp:ListItem>
        <asp:ListItem Text=" Choice 4" Value="val4"></asp:ListItem>
    </asp:DropDownList>
    <br/>
    <br/>
    <label class="fa fa-upload" style="cursor:pointer;margin-left:5%;">
        <small ID="Small2" runat="server" style="font-weight:bold;">Upload 
        file</small>
        <asp:FileUpload ID="FileUpload" runat="server" CssClass="form-control" 
            Style="display:none;" Width="400px" />
    </label>
</div>
<asp:Button ID="btnUpload" runat="server" CssClass="btn btn-primary pull- 
    right" OnClick="btnUpload" Text="Upload" CausesValidation="False" />
</div>

aspx.cs代码的一部分

public void btnUpload(object sender, EventArgs e) 
{
    String strConnection =
    ConfigurationManager.ConnectionStrings["connection"].ConnectionString;
    String path = Server.MapPath("/tempfile" + FileUpload1.FileName);
    String fileExt = Path.GetExtension(FileUpload1.PostedFile.FileName);

    if (FileUpload.HasFile) 
    {
        String tempfile = DateTime.Now.ToString("yyyyMMddhhmmss") +
        FileUpload1.FileName;
        FileUpload1.PostedFile.SaveAs(Server.MapPath("/tempfile/" + tempfile));

        String excelConnString = String.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source = " + path + "; Extended Properties = 'Excel 12.0; HDR = YES; READONLY = FALSE; '", path);

        using(OleDbConnection excelConnection = new OleDbConnection(excelConnString)) 
        {
            String ddlStr = report_upload.SelectedValue;

            //upload to db
            if (ddlStr == "val4") 
            {
                //Create OleDbCommand to fetch data from Excel
                using(OleDbCommand cmd = new OleDbCommand("SELECT * FROM [SheetA$]", excelConnection)) 
                {
                    excelConnection.Open();

                    using(OleDbDataReader dReader = cmd.ExecuteReader()) 
                    {
                        using(SqlBulkCopy sqlBulk = new SqlBulkCopy(strConnection)) 
                        {
                            // Destination table name
                            sqlBulk.DestinationTableName = "[db].[dbo].[Datatbl]";
                            sqlBulk.WriteToServer(dReader);
                        }
                    }

                    excelConnection.Close();
                }
            }
        }
    }
}

1 个答案:

答案 0 :(得分:0)

这样的事情应该有所帮助。

try {
    OpenFileDialog fBrowse = new OpenFileDialog();
    // With...
    "Excel files(*.xls)|*.xls|All files (*.*)|*.*".FilterIndex = "Import data from Excel file";
    fBrowse.Filter = "Import data from Excel file";
    if ((fBrowse.ShowDialog() == Windows.Forms.DialogResult.OK)) {
        string fname;
        fname = fBrowse.FileName;
        System.Data.OleDb.OleDbConnection MyConnection;
        System.Data.DataSet DtSet;
        System.Data.OleDb.OleDbDataAdapter MyCommand;
        MyConnection = new System.Data.OleDb.OleDbConnection(("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" 
                        + (fname + (";" + "Extended Properties=\"Excel 8.0;HDR=NO;IMEX=1\""))));
        MyCommand = new System.Data.OleDb.OleDbDataAdapter("select Columns names from [sheet$]", MyConnection);
        MyCommand.TableMappings.Add("Table", "Ur table name.");
        DtSet = new System.Data.DataSet();
        MyCommand.Fill(DtSet);
        // If dataset is not empty Then write code here to insert values to DB.
        MyConnection.Close();
    }

}
catch (Exception ex) {
    MessageBox.Show(ex.ToString);
}