OleDB读取excel但返回错误的数字格式

时间:2014-11-20 07:15:49

标签: c# excel oledb oledbconnection

我需要帮助在一列中读取混合类型的excel。 我有一个像这样的值的列

080810235707 -> text type
614810003481 -> text type
150130301951 -> text type
612130001653 -> text type
612130000354 -> text type
612130001926 -> text type
612810001877 -> text type
81130518669 -> numeric type
81130518614 -> numeric type
612130001686 -> text type
612130001119 -> text type

这是我的连接字符串:

string connectionString = String.Format(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + _view.FileName + ";Extended Properties = 'Excel 8.0; HDR=Yes; IMEX=1; ImportMixedTypes=Text; TypeGuessRows=0' ");

,当OleDB读取它时结果是错误的:

080810235707
614810003481
150130301951
612130001653
612130000354
612130001926
612810001877
8.11305e+010 -> the numeric become like this
8.11305e+010 -> the numeric become like this
612130001686
612130001119

如何设置OleDB,使其全部以文本类型读取,不是数字? 谢谢


修改

这是我读取excel的代码,如何实现转换列类型的代码:

DataSet ds = new DataSet();
string connectionString = String.Format(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + _view.FileName + ";Extended Properties = 'Excel 8.0; HDR=Yes; IMEX=1; ImportMixedTypes=Text; TypeGuessRows=0' ");


 OleDbConnection conn = new OleDbConnection(connectionString);
 conn.Open();
 dtSchemaTemp = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" });
 conn.Close();

strSheetTemp = dtSchemaTemp.Rows[i]["TABLE_NAME"].ToString();
OleDbDataAdapter adapter = new OleDbDataAdapter("SELECT * FROM [" + strSheetTemp + "]", connectionString);

adapter.Fill(ds, "ExcelData");
DataTable dt = ds.Tables["ExcelData"];

1 个答案:

答案 0 :(得分:0)

在阅读excel文件时,您可以使用NUMBERFORMAT格式化单元格,也可以通过将范围转换为TEXT来实现。

检查方法1)将工作表单元格格式化为TEXT:

 // Pull in all the cells of the worksheet
 Range cells = xlWorkBook.Worksheets[1].Cells;

 // set each cell's format to Text
 cells.NumberFormat = "@";

检查方法2)您可以在哪里阅读excel并将特定范围格式化为TEXT。

_workSheet = (Excel.Worksheet)_workBook.ActiveSheet;

//Replace A1 with your cell range
_range = _workSheet.get_Range("A1", "A1");

//set the format
_range.NumberFormat = "Text";

//save the changes back to the workbook
_workBook.Save()