2013-09-25 61 views
0

我一直在研究桌面應用程序,並且在導入Excel文件時遇到了一些問題。Excel文件導入 - 數據類型

一切都很好,但是當我從Excel工作表讀取數據時,它並沒有讀取所有的數字和字母。例如,如果該列的第一個單元格是數字,則不會從該列讀取字母。如果我手動將該類型更改爲該文本,那麼一切都很好。

這是我的示例代碼導入Excel工作表數據。

任何想法?

public static DataSet exceldata(string filelocation) 
{ 
    DataSet ds = new DataSet(); 

    OleDbCommand excelCommand = new OleDbCommand(); 
    OleDbDataAdapter excelDataAdapter = new OleDbDataAdapter(); 

    string excelConnStr = String.Format("Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties=\"Excel 4.0;HDR=YES;IMEX=1;Importmixedtypes=text;typeguessrows=0;\"", filelocation); 

    OleDbConnection excelConn = new OleDbConnection(excelConnStr); 

    excelConn.Open(); 

    DataTable dtPatterns = new DataTable(); 
    excelCommand = new OleDbCommand("SELECT * FROM [Sheet1$]", excelConn); 

    excelDataAdapter.SelectCommand = excelCommand; 

    excelDataAdapter.Fill(dtPatterns); 

    ds.Tables.Add(dtPatterns); 

    return ds; 

} 

回答

2
System.out.println(cell.toString());//here is the problem 

toString()方法返回對象的字符串表示。通常,toString方法返回一個「文本表示」該對象的字符串。

使用cell.getStringCellValue()

代替

cell.toString()

而且數比例的使用需要。

對於必須使用

getNumericCellValue(),把一個條件有

if(cell!=null) 
      { 
       int type = cell.getCellType(); 
       if (type == HSSFCell.CELL_TYPE_STRING) 
        System.out.println(cell.getRichStringCellValue().toString()); 
       else if (type == HSSFCell.CELL_TYPE_NUMERIC) 

        String[] splits = String.valueOf(cell.getNumericCellValue()).split("."); 

       System.out.println(splits[0]); 
       else if (type == HSSFCell.CELL_TYPE_BOOLEAN) 
        System.out.println(cell.getBooleanCellValue()); 
       else if (type == HSSFCell.CELL_TYPE_BLANK) 
        System.out.println(cell.getColumnIndex() + "] = BLANK CELL"); 
      } 
數值
相關問題