Excel文件导入 - 数据类型

时间:2013-09-25 05:37:03

标签: c# .net winforms excel-interop winforms-interop

我一直在使用桌面应用程序,我对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;

}

1 个答案:

答案 0 :(得分:2)

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

toString()方法返回对象的字符串表示形式。通常,toString方法返回一个“文本表示”此对象的字符串。

使用cell.getStringCellValue()

代替

  

cell.toString()

需要使用propor。

对于数值,您必须使用

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");
            }