1
我正在读取Excel表格中的值。列通常包含String
,但有时可能包含数字值。将Excel工作表读取为可数字数值时读取为空白。如果列的值为数字,则读取Excel表格,然后在数据表格中返回空值
它读取90004为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
我的代码:
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;
}
正如这里写的http://stackoverflow.com/questions/3206915/dbnull-in-non-empty-cell-when-reading-excel-file-through-oledb问题是,提供程序将值设置为null如果有更多的字符串值,那么数字值。也许这会帮助你。可悲的是,目前我无法解决您的问题。 – Boot750
它读取90004为空,但如果我按数字排序该列它读取数值,并给出字符串值为空,如果我按字符串排序此列,然后它读取字符串值,并给出数字为空。 – poonam
您可以尝试将连接字符串中的IMEX = 2更改为IMEX = 1。 IMEX = 1应该将所有内容导入为文本。你可以通过使用int32.TryParse来检查你的c#代码,如果它是一个数字值。 – Boot750