>我需要帮助在一列中阅读混合类型的 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"];
在读取 excel 文件时,您可以使用 数字格式 格式化单元格,也可以通过将范围转换为文本来做到这一点。
检查方法 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()