【发布时间】:2017-11-11 08:44:36
【问题描述】:
我使用这个函数来读取excel文件到数据表:
public static DataTable exceldata(string filePath)
{
try
{
DataTable dtexcel = new DataTable();
bool hasHeaders = false;
string HDR = hasHeaders ? "Yes" : "No";
string strConn;
if (filePath.Substring(filePath.LastIndexOf('.')).ToLower() == ".xlsx")
strConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filePath + ";Extended Properties=\"Excel 12.0;IMEX=1;HDR=YES;TypeGuessRows=0;ImportMixedTypes=Text\"";
else
strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filePath + ";Extended Properties=\"Excel 8.0;IMEX=1;HDR=YES;TypeGuessRows=0;ImportMixedTypes=Text\"";
OleDbConnection conn = new OleDbConnection(strConn);
conn.Open();
DataTable schemaTable = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" });
DataRow schemaRow = schemaTable.Rows[0];
string sheet = schemaRow["TABLE_NAME"].ToString();
if (!sheet.EndsWith("_"))
{
string query = "SELECT * FROM [" + sheet + "]";
OleDbDataAdapter daexcel = new OleDbDataAdapter(query, conn);
dtexcel.Locale = CultureInfo.CurrentCulture;
daexcel.Fill(dtexcel);
}
conn.Close();
return dtexcel;
}
catch (Exception ex)
{
return null;
}
}
我的问题是:当 Excel 文件有一些格式看起来像数字的单元格(例如:301/1、181/3 ....)时,数据表在该单元格中返回空值。
如何将 Excel 文件读取到数据表中,将单元格作为字符串,而不是检测到数字?
【问题讨论】:
-
尝试将底层excel格式化为文本
-
你能附上那个电子表格吗(通过 DropBox 或 G-drive 之类的)?我相信你,但我从未见过也无法复制这个问题。
标签: c# excel string datatable numbers