【问题标题】:Unable to enter Excel upload data into SQL Server database using C#无法使用 C# 将 Excel 上传数据输入 SQL Server 数据库
【发布时间】:2018-06-24 14:25:44
【问题描述】:

我正在尝试创建一个函数来选择要上传的文件类型,并将 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();
                }
            }
        }
    }
}

【问题讨论】:

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


    【解决方案1】:

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

    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);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-04-17
      • 1970-01-01
      • 1970-01-01
      • 2020-04-17
      • 2015-10-19
      • 1970-01-01
      • 2019-12-24
      相关资源
      最近更新 更多