【问题标题】:Data is not saving while excel sheet uploading using asp.net C#使用asp.net C#上传Excel工作表时数据不保存
【发布时间】:2019-11-30 05:09:52
【问题描述】:

上传 Excel 表格时数据未保存在数据库中。

我正在使用 ASP.NET 和 C# 上传 Excel 工作表并将其数据保存到数据库中。我是 .net 新手,我从 https://www.c-sharpcorner.com/UploadFile/0c1bb2/uploading-and-downloading-excel-files-from-database-using-as/ 获得帮助。

文件上传成功,显示mag,但数据没有保存在数据库中。

这是我的代码:

protected void Button5_Click(object sender, EventArgs e)
{
    lblMessage.Visible = true;

    string filePath = FileUpload1.PostedFile.FileName; // getting the file path of uploaded file  
    string filename1 = Path.GetFileName(filePath); // getting the file name of uploaded file  
    string ext = Path.GetExtension(filename1); // getting the file extension of uploaded file  
    string type = String.Empty;

    string CustomerID = String.Empty;
    string AddressType = String.Empty;
    string AddressLine1 = String.Empty;
    string AddressLine2 = String.Empty;
    string StateID = String.Empty;
    string DistrictID = String.Empty;
    string PinCode = String.Empty;
    string ResidencePhoneNo = String.Empty;
    string OfficePhoneNo = String.Empty;
    string Mobile = String.Empty;
    string EmailID = String.Empty;

    if (!FileUpload1.HasFile)
    {
        lblMessage.Text = "Please Select File"; //if file uploader has no file selected  
    }
    else if (FileUpload1.HasFile)
    {
        try
        {
            switch (ext) // this switch code validate the files which allow to upload only excel file you can change it for any file  
            {
                case ".xls":
                    type = "application/vnd.ms-excel";
                    break;

                case ".xlsx":
                    type = "application/vnd.ms-excel";
                    break;
            }

            if (type != String.Empty)
            {
                Stream fs = FileUpload1.PostedFile.InputStream;
                BinaryReader br = new BinaryReader(fs); //reads the   binary files  
                Byte[] bytes = br.ReadBytes((Int32)fs.Length); //counting the file length into bytes                               

                try
                {
                     SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["Odisha_2May2019ConnectionString"].ConnectionString);
                     conn.Open();

                     String query = "insert into CustomAddress( AddressType, CustomerID, AddressLine2, AddressLine1, PinCode, ResidencePhoneNo, " +
                            "OfficePhoneNo, Mobile, EmailID)" + "values ( @AddressType, @CustomerID, @AddressLine2, @AddressLine1, " +
                            " @PinCode, @ResidencePhoneNo, @OfficePhoneNo, @Mobile, @EmailID)";
                     query = "insert into CustomAddress(StateID, DistrictID) select s.StateID, d.DistrictID from State s, District d Where s.StateName=@StateID and d.DistName=@DistrictID";

                     SqlCommand com = new SqlCommand(query, conn);
                     com.Parameters.Add("@CustomerID", SqlDbType.VarChar, 20).Value = CustomerID;
                     com.Parameters.Add("@AddressType", SqlDbType.VarChar, 20).Value = "1";
                     com.Parameters.Add("@AddressLine2", SqlDbType.VarChar, 20).Value = AddressLine2;
                     com.Parameters.Add("@AddressLine1", SqlDbType.VarChar, 20).Value = AddressLine1;
                     com.Parameters.Add("@StateID", SqlDbType.VarChar, 20).Value = StateID;
                     com.Parameters.Add("@DistrictID", SqlDbType.VarChar, 20).Value = DistrictID;
                     com.Parameters.Add("@PinCode", SqlDbType.VarChar, 20).Value = PinCode;
                     com.Parameters.Add("@ResidencePhoneNo", SqlDbType.VarChar, 20).Value = ResidencePhoneNo;
                     com.Parameters.Add("@OfficePhoneNo", SqlDbType.VarChar, 20).Value = OfficePhoneNo;
                     com.Parameters.Add("@Mobile", SqlDbType.VarChar, 20).Value = Mobile;
                     com.Parameters.Add("@EmailID", SqlDbType.VarChar, 20).Value = EmailID;                                                     

                     com.ExecuteNonQuery();

                     lblMessage.ForeColor = System.Drawing.Color.Green;
                     lblMessage.Text = "File Uploaded Successfully";
                     conn.Close();
                 }
                 catch (Exception ex)
                 {
                     Response.Write("error" + ex.ToString());
                 }
             }
         }
    }
}

我只是想知道,如何从保存在数据库中的 Excel 工作表中获取数据。或者纠正我的错误。

【问题讨论】:

  • 您好,您忘记读取excel文件
  • 如果我想使用这段代码,那么我该如何读取excel文件。

标签: c# asp.net .net excel


【解决方案1】:

你可以用这个方法从excel中读取数据

  private DataTable GetTableFromExcel()
    {

        Workbook book = new Workbook();
        book.InvalidFormatException += book_InvalidFormatException;
        book.LoadDocument(FilePath);
        Worksheet sheet = book.Worksheets.ActiveWorksheet;
        Range range = sheet.GetUsedRange();
        DataTable table = sheet.CreateDataTable(range, false);
        DataTableExporter exporter = sheet.CreateDataTableExporter(range, table, false);
        exporter.CellValueConversionError += exporter_CellValueConversionError;
        exporter.Export();
        return table;
    }

当你点击按钮时调用方法

protected void Button5_Click(object sender, EventArgs e)
{
//your code
   else if (FileUpload1.HasFile)
{
  DataTable table = GetTableFromExcel();
  for (int i = 1; i < table.Rows.Count; i++)
// your code 2
}
}

【讨论】:

    【解决方案2】:

    另一种使用 System.Data.OleDb 命名空间读取 excel 的方法

        private static DataTable ReadExcelData(string FilePath)
        {
            string conStr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0}; Extended Properties='Excel 8.0;HDR=Yes'"; ;
            conStr = String.Format(conStr, FilePath);
            OleDbConnection connExcel = new OleDbConnection(conStr);
            OleDbCommand cmdExcel = new OleDbCommand();
            OleDbDataAdapter oda = new OleDbDataAdapter();
            DataTable dt = new DataTable();
            cmdExcel.Connection = connExcel;
    
            //Get the name of First Sheet
            connExcel.Open();
            DataTable dtExcelSchema;
            dtExcelSchema = connExcel.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
            string SheetName = dtExcelSchema.Rows[0]["TABLE_NAME"].ToString();
            connExcel.Close();
    
            //Read Data from First Sheet
            connExcel.Open();
            cmdExcel.CommandText = "SELECT * From [" + SheetName + "]";
            oda.SelectCommand = cmdExcel;
            oda.Fill(dt);
            connExcel.Close();
    
    
            return dt;
        }
    

    在按钮点击时,您可以如下调用

     protected void btn_Click(object sender, EventArgs e)
        {
    
            if (FileUpload1.HasFile)
            {
                DataTable dt = ReadExcelData(@"your Excel Document Path");
                foreach (DataRow dr in dt.Rows)
                {
                    //Your Code to insert record into the database
                }
            }
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多