2012-11-04 64 views
0

您好我想从一个网页的Excel电子表格中加载数据到sql,我得到一个“不能隐式转换类型'string'到'decimal”错误我试过不同的方法纠正这一点,但没有任何工作。从excel导入到sql格式错误

namespace CarpartsStore.Dealers 
{ 

partial class DealerHome : System.Web.UI.Page 
{ 

    protected void ButtonUpload_Click(object sender, System.EventArgs e) 
    { 
     PanelUpload.Visible = true; 
     PanelView.Visible = false; 
     PanelImport.Visible = false; 
    } 


    protected OleDbCommand ExcelConnection() 
    { 

     // Connect to the Excel Spreadsheet 
     string xConnStr = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + Server.MapPath("~/ExcelImport.xls") + ";" + "Extended Properties=Excel 8.0;"; 

     // create your excel connection object using the connection string 
     OleDbConnection objXConn = new OleDbConnection(xConnStr); 
     objXConn.Open(); 

     // use a SQL Select command to retrieve the data from the Excel Spreadsheet 
     // the "table name" is the name of the worksheet within the spreadsheet 
     // in this case, the worksheet name is "Members" and is coded as: [Members$] 
     OleDbCommand objCommand = new OleDbCommand("SELECT * FROM [Products$]", objXConn); 
     return objCommand; 



    } 

    protected void ButtonView_Click(object sender, System.EventArgs e) 
    { 
     PanelUpload.Visible = false; 
     PanelView.Visible = true; 
     PanelImport.Visible = false; 

     // Create a new Adapter 
     OleDbDataAdapter objDataAdapter = new OleDbDataAdapter(); 

     // retrieve the Select command for the Spreadsheet 
     objDataAdapter.SelectCommand = ExcelConnection(); 

     // Create a DataSet 
     DataSet objDataSet = new DataSet(); 
     // Populate the DataSet with the spreadsheet worksheet data 
     objDataAdapter.Fill(objDataSet); 

     // Bind the data to the GridView 
     GridViewExcel.DataSource = objDataSet.Tables[0].DefaultView; 
     GridViewExcel.DataBind(); 
    } 


    protected void ButtonImport_Click(object sender, System.EventArgs e) 
    { 
     PanelUpload.Visible = false; 
     PanelView.Visible = false; 
     PanelImport.Visible = true; 
     LabelImport.Text = ""; 
     // reset to blank 

     // retrieve the Select Command for the worksheet data 
     OleDbCommand objCommand = new OleDbCommand(); 
     objCommand = ExcelConnection(); 

     // create a DataReader 
     OleDbDataReader reader; 
     reader = objCommand.ExecuteReader(); 


     // create variables for the spreadsheet columns 
     int ProductID = 0; 
     int MakeID = 0; 
     int DealerID = 0; 
     string PartNumber = ""; 
     string Description = ""; 
     decimal UnitCost = 0.00M; 
     decimal Postage = 0.00M; 
     int QtyAvailable = 0; 
     string UserName = ""; 
     string Make = ""; 


     int counter = 0; 
     // used for testing your import in smaller increments 

     while (reader.Read()) 
     { 
      counter = counter + 1; 
      // counter to exit early for testing... 

      // set default values for loop 
      ProductID = 0; 
      MakeID = 0; 
      DealerID = 0; 



      PartNumber = GetValueFromReader(reader,"PartNumber"); 
      Description = GetValueFromReader(reader,"Description"); 


      UnitCost = GetValueFromReader(reader,"UnitCost"); 
      Postage = GetValueFromReader(reader, "Postage"); 


      QtyAvailable = GetValueFromReader(reader,"QtyAvailable"); 
      UserName = GetValueFromReader(reader,"UserName"); 
      Make = GetValueFromReader(reader,"Make"); 


      // Insert any required validations here... 

      MakeID = GetMakeID(Make); 
      DealerID = GetDealerID(UserName); 


      //retrieve the MakeID 
      ProductID = ImportIntoProducts(PartNumber, Description, UnitCost, Postage, QtyAvailable, MakeID, DealerID); 

      LabelImport.Text = LabelImport.Text + ProductID + PartNumber + " " + Description + " " + UnitCost + " " + Postage + " " + QtyAvailable + " " + UserName + " Make_id: " + MakeID + " " + Make + "<br>"; 
      //If counter > 2 Then ' exit early for testing, comment later... 
      // Exit While 
      //End If 

     } 
     reader.Close(); 

    } 



    protected string GetValueFromReader(OleDbDataReader myreader, string stringValue) 
    { 
     object val = myreader[stringValue]; 
     if (val != DBNull.Value) 
      return val.ToString(); 
     else 
      return ""; 
    } 


    protected void ButtonUploadFile_Click(object sender, System.EventArgs e) 
    { 

     if (FileUploadExcel.HasFile) 
     { 


      try 
      { 
       // alter path for your project 

       FileUploadExcel.SaveAs(Server.MapPath("~/ExcelImport.xls")); 
       LabelUpload.Text = "Upload File Name: " + 
        FileUploadExcel.PostedFile.FileName + "<br>" + 
        "Type: " + FileUploadExcel.PostedFile.ContentType + 
        " File Size: " + FileUploadExcel.PostedFile.ContentLength + 
        " kb<br>"; 
      } 
      catch (System.NullReferenceException ex) 
      { 
       LabelUpload.Text = "Error: " + ex.Message; 
      } 
     } 
     else 
     { 
      LabelUpload.Text = "Please select a file to upload."; 
     } 

    } 



    protected int GetMakeID(string MakeName) 
    { 

     int makeID = 0; 
     try 
     { 
      CarpartsStore.DataSets.SSSProductsDataSetTableAdapters.MakesTableAdapter SSAdapter = new CarpartsStore.DataSets.SSSProductsDataSetTableAdapters.MakesTableAdapter(); 
      SSSProductsDataSet.MakesDataTable SSDataTable = null; 
      SSDataTable = SSAdapter.GetMakeByName(MakeName); 
      // see if the category already exists in the table, if not insert it 
      if (SSDataTable != null) 
      { 
       if (SSDataTable.Rows.Count > 0) 
       { 
        if (SSDataTable[0].MakeID > 0) 
        { 
         makeID = SSDataTable[0].MakeID; 
        } 
       } 
      } 
      if (makeID == 0) 
      { 
       // if it is still 0, then insert it into the table 
       // retrieve the identity key category_id from the insert 
       makeID = (int)SSAdapter.InsertMakeQuery(MakeName); 
       // if this fails to return the proper category_id, make sure to 
       // set the InsertCategoryQuery ExecuteMode Property to Scalar 
      } 
      return makeID; 
     } 
     catch (System.NullReferenceException ex) 
     { 
      LabelImport.Text = LabelImport.Text + ex.Message; 
      return 0; 
     } 

    } 

    protected int GetDealerID(string UserName) 
    { 

     int DealerID = 0; 
     try 
     { 
      CarpartsStore.DataSets.SSSProductsDataSetTableAdapters.DealersTableAdapter SSAdapter = new CarpartsStore.DataSets.SSSProductsDataSetTableAdapters.DealersTableAdapter(); 
      SSSProductsDataSet.DealersDataTable SSDataTable = null; 
      SSDataTable = SSAdapter.GetDealersByUserName(UserName); 
      // see if the User already exists in the table, if not insert it 
      if (SSDataTable != null) 
      { 
       if (SSDataTable.Rows.Count > 0) 
       { 
        if (SSDataTable[0].DealerID > 0) 
        { 
         DealerID = SSDataTable[0].DealerID; 
        } 
       } 
      } 
      if (DealerID == 0) 
      { 
       // if it is still 0, then insert it into the table 
       // retrieve the identity key category_id from the insert 
       DealerID = 0; 
       // if this fails to return the proper category_id, make sure to 
       // set the InsertCategoryQuery ExecuteMode Property to Scalar 
      } 
      return DealerID; 
     } 
     catch (System.NullReferenceException ex) 
     { 
      LabelImport.Text = LabelImport.Text + ex.Message; 
      return 0; 
     } 

    } 


    protected int ImportIntoProducts(string PartNumber, string Description, decimal UnitCost, decimal Postage, int QtyAvailable, int MakeID, int DealerID) 
    { 


     // make sure values don't exceed column limits 
     PartNumber = Left(PartNumber, 50); 
     Description = Left(Description, 300); 
     UnitCost = Convert.ToDecimal(UnitCost); 





     int ProductID = 0; 
     try 
     { 
      CarpartsStore.DataSets.SSSProductsDataSetTableAdapters.ProductsTableAdapter SSAdapter = new CarpartsStore.DataSets.SSSProductsDataSetTableAdapters.ProductsTableAdapter(); 
      SSSProductsDataSet.ProductsDataTable SSDataTable = null; 
      SSDataTable = SSAdapter.GetProductsByPartNumberDealer(PartNumber, DealerID); 
      // see if the category already exists in the table, if not insert it 
      if (SSDataTable != null) 
      { 
       if (SSDataTable.Rows.Count > 0) 
       { 
        if (SSDataTable[0].ProductID > 0) 
        { 
         ProductID = SSDataTable[0].ProductID; 
         LabelImport.Text = LabelImport.Text + "<font color=blue>PartNumber Found, Not Imported: " + " ID: " + ProductID + " " + PartNumber + " " + Description + "" + UnitCost + "" + Postage + ".</font><br>"; 
        } 
       } 
      } 
      if (ProductID == 0) 
      { 
       // if it is still 0, then insert it into the table 
       // retrieve the identity key ProductID from the insert 
       ProductID = Convert.ToInt32(SSAdapter.InsertProductQuery(PartNumber, Description,UnitCost, Postage, QtyAvailable, MakeID, DealerID)); 
       LabelImport.Text = LabelImport.Text + "<font color=white>Part Number Imported: " + " ID: " + ProductID + " " + PartNumber + " " + Description + " Cost: " + UnitCost + ".</font><br>"; 
      } 
      return ProductID; 
     } 
     catch (System.NullReferenceException ex) 
     { 
      LabelImport.Text = LabelImport.Text + "<font color=red>" + ex.Message  + "</font><br>"; 
      return 0; 
     } 

    } 



    // http://www.mgbrown.com/PermaLink68.aspx 
    public static string Left(string text, int length) 
    { 
     if (length < 0) 
      throw new ArgumentOutOfRangeException("length", length, "length must be > 0"); 
     else if (length == 0 || text.Length == 0) 
      return ""; 
     else if (text.Length <= length) 
      return text; 
     else 
      return text.Substring(0, length); 

    } 

} 
} 
+0

这里有一个代码_lot_。你从哪里得到错误?什么是产生错误的运行时间值? – David

+0

您需要调试并查看导致异常的数据究竟是什么,它可能是Excel数据格式错误,或者它可能只是一个空字符串,异常消息已经如此详细以至于没有调试,我认为您不能想办法。 此外,如果这是一次性的东西,我强烈建议继续使用SQL Server导入工具来完成这项工作 –

+0

嗨造成问题的三条线是这些 UnitCost = GetValueFromReader(reader,“UnitCost”); 邮资= GetValueFromReader(阅读器,“邮资”); QtyAvailable = GetValueFromReader(reader,“QtyAvailable”);前两个是小数,最后一个是int,我已经尝试从字符串转换,但这剂量工作要么 – dsp100

回答

0

下面的代码变化将让你的代码运行:

try 
{ 
    UnitCost = GetValueFromReader(reader,"UnitCost"); 
} 
catch(Exception) 
{ 
    // put a breakpoint here to find the problem using the debugger 
} 

try 
{ 
    Postage = GetValueFromReader(reader, "Postage"); 
} 
catch(Exception) 
{ 
    // put a breakpoint here to find the problem using the debugger 
} 

你真正想要做的是了解源数据是如何造成的错误。 (也许你在源数据中有一个空值或非数字值)。

让这样的代码可能(也可能会)将数据错误引入到系统的其他部分。