2014-05-25 48 views
0

我是VB.net 2010的新手。我試圖從我的項目中讀寫excel。目前我正面臨着數據類型轉換的問題。我無法將對象數據類型轉換爲整數數據類型以進行計算。它不斷給我錯誤: 「從字符串轉換」上傳序列號「到類型」整數「無效」在vb.net中轉換對象數據類型

這是我的代碼。 (在檢查代碼之前一定要添加引用,Project-Add References-COM Object-Microsoft Excel COM對象12.0)

Imports System.IO 
Imports Excel = Microsoft.Office.Interop.Excel 

Imports System.Drawing 

Imports System.Windows.Forms 

Imports Microsoft.Office 

Imports Microsoft.Office.Interop.Excel 


Public NumberofLayupsinStackingLibrary As Object 

Public path As String = Directory.GetCurrentDirectory() 

Public xlApp As Excel.Application 

Public xlWorkBook As Excel.Workbook 

Public xlWorkSheet As Excel.Worksheet 


xlApp = New Excel.ApplicationClass 

xlWorkBook = xlApp.Workbooks.Open(path + "\StackingLibrary") 

xlWorkSheet = xlWorkBook.Worksheets("sheet1") 

NumberofLayupsinStackingLibrary = xlWorkSheet.Cells(1, 1).value 

Dim alpha As Integer = CInt(NumberofLayupsinStackingLibrary) - 1 

xlWorkBook.Close(SaveChanges:=False) 

xlApp.Quit() 

請告訴我該怎麼做。我將不勝感激。

+0

您確定已經複製完全您的代碼嗎? – Steve

回答

1

錯誤消息

從字符串「序列號上籃」鍵入「整型」的轉換是無效的

基本上說明了一切:

您正試圖轉換值爲"Serial Number Of Layup"爲整數。顯然,這是不可能的。這個文本應該代表什麼數字值?

看着你的代碼顯示你在那裏只有一個整數轉換:CInt(NumberofLayupsinStackingLibrary)。進一步閱讀代碼可以看出NumberofLayupsinStackingLibrary是從xlWorkSheet.Cells(1, 1)填充的。

結論:在工作表中細胞1/1包含文本Serial Number Of Layup,這是不的整數,並且不能被轉換爲一個。您的程序按預期行事。

0

使用以下代碼從Excel工作表中讀取並將其寫入gridview。

> using System; using System.Collections.Generic; using System.Linq; 
> using System.Web; using System.Web.UI; using 
> System.Web.UI.WebControls; using System.Data; using System.Data.Odbc; 
> using System.Data.OleDb; using System.IO; using 
> System.Web.Script.Services; using System.Web.Services; 
> 
> namespace NEWCICR { 
>  public partial class newer : System.Web.UI.Page 
>  { 
>   DataTable dt = new DataTable(); 
> 
> 
>   //Declare Variable (property) 
> 
>   string currFilePath = string.Empty; //File Full Path 
>   string currFileExtension = string.Empty; //File Extension 
> 
>   //Page_Load Event, Register Button Click Event 
> 
>   protected void Page_Load(object sender, EventArgs e) 
>   { 
>  this.btnRead.Click += new EventHandler(btnRead_Click); 
> 
>   } 
> 
>   //Button Click Event 
> 
> 
>   protected void btnRead_Click(object sender, EventArgs e) 
>   { 
> 
>    Upload(); //Upload File Method 
>    if (this.currFileExtension == ".xlsx" || this.currFileExtension == ".xls") 
>    { 
>     DataTable dt = ReadExcelToTable(currFilePath); //Read Excel File (.XLS and .XLSX Format) 
>    } 
>    else if (this.currFileExtension == ".csv") 
>    { 
>     DataTable dt = ReadExcelWithStream(currFilePath); //Read .CSV File 
>    } 
> 
> 
> 
>   } 
> 
>   ///<summary> 
> 
>   ///Upload File to Temporary Category 
> 
>   ///</summary> 
> 
>   private void Upload() 
>   { 
>    HttpPostedFile file = this.fileSelect.PostedFile; 
>    string fileName = file.FileName; 
>    string tempPath = System.IO.Path.GetTempPath(); //Get Temporary File Path 
>    fileName = System.IO.Path.GetFileName(fileName); //Get File Name (not including path) 
>    this.currFileExtension = System.IO.Path.GetExtension(fileName); //Get File Extension 
>    this.currFilePath = tempPath + fileName; //Get File Path after Uploading and Record to Former Declared Global Variable 
>    file.SaveAs(this.currFilePath); //Upload 
>   } 
> 
>   ///<summary> 
>   ///Method to Read XLS/XLSX File 
>   ///</summary> 
>   ///<param name="path">Excel File Full Path</param> 
>   ///<returns></returns> 
> 
>   private DataTable ReadExcelToTable(string path) 
>   { 
> 
>    //Connection String 
> 
>    string connstring = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Extended 
> Properties='Excel 8.0;HDR=NO;IMEX=1';"; // Extra blank space cannot 
> appear in Office 2007 and the last version. And we need to pay 
> attention on semicolon. 
> 
>    // string connstring = "Provider=Microsoft.JET.OLEDB.4.0;Data Source=" + path + ";Extended 
> Properties='Excel 8.0;HDR=NO;IMEX=1';"; //This connection string is 
> appropriate for Office 2007 and the older version. We can select the 
> most suitable connection string according to Office version or our 
> program. 
> 
>    using (OleDbConnection conn = new OleDbConnection(connstring)) 
>    { 
>     conn.Open(); 
>     DataTable sheetsName = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, 
> null, null, "Table" }); //Get All Sheets Name 
>     string firstSheetName = sheetsName.Rows[0][2].ToString(); //Get the First Sheet Name 
>     string sql = string.Format("SELECT * FROM [{0}],firstSheetName"); 
>     //Query String 
>     OleDbDataAdapter ada = new OleDbDataAdapter(sql, connstring); 
>     DataSet set = new DataSet(); 
>     ada.Fill(set); 
>     return set.Tables[0]; 
>    } 
>   } 
> 
>   ///<summary> 
>   ///Method to Read CSV Format 
>   ///</summary> 
>   ///<param name="path">Read File Full Path</param> 
>   ///<returns></returns> 
> 
> 
>   private DataTable ReadExcelWithStream(string path) 
>   { 
> 
>    bool isDtHasColumn = false; //Mark if DataTable Generates Column 
>    StreamReader reader = new StreamReader(path, System.Text.Encoding.Default); //Data Stream 
>    while (!reader.EndOfStream) 
>    { 
>     string message = reader.ReadLine(); 
>     string[] splitResult = message.Split(new char[] { ',' }, StringSplitOptions.None); //Read One Row and Separate by Comma, 
> Save to Array 
>     DataRow row = dt.NewRow(); 
>     for (int i = 0; i < splitResult.Length; i++) 
>     { 
>      if (!isDtHasColumn) //If not Generate Column 
>      { 
>       dt.Columns.Add("column" + i, typeof(string)); 
>      } 
>      row[i] = splitResult[i]; 
>     } 
>     dt.Rows.Add(row); 
>     isDtHasColumn = true; //Mark the Existed Column after Read the First Row, Not Generate Column after Reading Later Rows 
>    } 
> 
>    
>    GridView1.DataSource = dt; 
>    GridView1.DataBind(); 
>    DataTable js = dt; 
> 
> 
>    return dt; 
>   } 
> 
> 
> 
>  } 
> 
> }