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