在读取Excel表时,如果列的值是数字,那么它在数据表中返回null
本文关键字:null 数据表 数字 返回 Excel 读取 表时 如果 | 更新日期: 2023-09-27 18:03:26
我正在读取Excel表中的值。列通常包含String
,但有时也可能包含数值。当读取Excel表格到可数据的数值时,读取为空白。
它读取90004作为null
,但是如果我按数字排序这一列,它读取数值并给出字符串值作为null
,如果我按字符串排序这一列,那么它读取字符串值并给出数值为null。
AC62614 abc EA MISC
AC62615 pqr EA MISC
AC62616 xyz EA MISC
AC62617 test EA 90004
AC62618 test3 TO MISC
AC62619 test3 TO STEEL
my code:
public static DataTable ReadExcelFile(FileUpload File1, string strSheetName)
{
string strExtensionName = "";
string strFileName = System.IO.Path.GetFileName(File1.PostedFile.FileName);
DataTable dtt = new DataTable();
if (!string.IsNullOrEmpty(strFileName))
{
//get the extension name, check if it's a spreadsheet
strExtensionName = strFileName.Substring(strFileName.IndexOf(".") + 1);
if (strExtensionName.Equals("xls") || strExtensionName.Equals("xlsx"))
{
/*Import data*/
int FileLength = File1.PostedFile.ContentLength;
if (File1.PostedFile != null && File1.HasFile)
{
//upload the file to server
//string strServerPath = "~/FolderName";
FileInfo file = new FileInfo(File1.PostedFile.FileName);
string strServerFileName = file.Name;
string strFullPath = HttpContext.Current.Server.MapPath("UploadedExcel/" + strServerFileName);
File1.PostedFile.SaveAs(strFullPath);
//open connection out to read excel
string strConnectionString = string.Empty;
if (strExtensionName == "xls")
strConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source="
+ strFullPath
+ ";Extended Properties='"Excel 8.0;HDR=Yes;IMEX=2'"";
else if (strExtensionName == "xlsx")
strConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source="
+ strFullPath
+ ";Extended Properties='"Excel 12.0;HDR=Yes;IMEX=2'"";
if (!string.IsNullOrEmpty(strConnectionString))
{
OleDbConnection objConnection = new OleDbConnection(strConnectionString);
objConnection.Open();
DataTable oleDbSchemaTable = objConnection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
bool blExists = false;
foreach (DataRow dtr in oleDbSchemaTable.Rows)
{
//reads from the spreadsheet called 'Sheet1'
if (dtr["TABLE_NAME"].ToString() == "" + strSheetName + "$")
{
blExists = true;
break;
}
}
if (blExists)
{
OleDbCommand objCmd = new OleDbCommand(string.Format("Select * from [{0}$]", strSheetName), objConnection);
OleDbDataAdapter objAdapter1 = new OleDbDataAdapter();
objAdapter1.SelectCommand = objCmd;
DataSet objDataSet = new DataSet();
objAdapter1.Fill(objDataSet);
objConnection.Close();
dtt = objDataSet.Tables[0];
}
}
}
}
}
return dtt;
}
如果将connectionstring中的IMEX=2更改为IMEX= 1,则列将被解释为文本。然后,您可以获取Sheet的所有数据并使用Int32.TryParse()检查值是否为数字。
连接字符串:
"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + Path + ";Extended Properties='"Excel 8.0;HDR=Yes;IMEX=1'"
IMEX=1
For Read All value as Text from Excel fileHDR =Yes
For Excel第一行作为列读取IMEX=1
not use Than数值将被NULL读取