【问题标题】:OleDB read excel but return wrong number formatOleDB 读取 excel 但返回错误的数字格式
【发布时间】:2014-11-20 16:38:37
【问题描述】:

我需要帮助来阅读一列中混合类型的 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"];

【问题讨论】:

  • @vba4all 我相信如果我使用您上面给出的链接中的代码,它会起作用。但是该应用程序将被很多人使用,并且不可能将Schema.ini 插入所有文件夹,因为用户将从任何文件夹上传文件。但是感谢您的帮助

标签: c# excel oledb oledbconnection


【解决方案1】:

在读取 excel 文件时,您可以使用 NUMBERFORMAT 格式化单元格,也可以将范围转换为 TEXT。

检查方法1)将工作表单元格格式化为文本的位置:

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

【讨论】:

  • 如何将一列值转换为字符串??
  • 好的,但是我如何将您的代码实现到我的代码中?我不知道如何使用它。我已经对上面的问题进行了更新。我把我的一些代码用来读取 excel 文件。谢谢@PareshJ
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-07-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-07-03
  • 1970-01-01
相关资源
最近更新 更多