2014-05-25 2 views
0

저는 VB.net 2010을 처음 사용합니다. 저는 프로젝트에서 Excel에서 읽고 쓰려고합니다. 현재 데이터 형식 변환 문제가 있습니다. 내 계산을 위해 개체 데이터 형식을 정수 데이터 형식으로 변환 할 수 없습니다. 계속 오류가 발생합니다 : "정수"를 입력하면 "정수의 유형"에서 문자열 "문자열로 변환"이 유효하지 않습니다 "vb.net에서 객체 데이터 유형 변환

여기 내 코드입니다.

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() 

가 무엇을 가르쳐주세요 (코드 참조를 추가해야합니다 확인하기 전에 참조-COM 객체 Microsoft Excel에서 COM은 12.0 개체 프로젝트 - 추가). 나는 감사 할 것이다. 당신은 변환하고자하는

을 :

+0

정확한 코드를 복사 했습니까? – Steve

답변

1

오류 메시지 '정수'를 입력하는 문자열 "레이 업의 일련 번호"에서

변환

은 기본적으로 모두를 말한다 유효하지 않습니다 값은 "Serial Number Of Layup"이고 정수입니다. 분명히 이것은 불가능합니다. 이 텍스트는 어떤 숫자 값을 나타내야합니까?

코드를 보면 거기에 정수 변환이 하나만 있음을 알 수 있습니다 : CInt(NumberofLayupsinStackingLibrary). 코드를 자세히 읽으면 NumberofLayupsinStackingLibraryxlWorkSheet.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; 
>   } 
> 
> 
> 
>  } 
> 
> }