2013-09-25 55 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"); 
      } 
数值
相关问题