我正在使用控制檯應用程序腳本將Excel文件導入到Sql Server數據庫中。當我選擇從Excel工作表中只有兩列,LocalSKU和庫存量將Excel導入到Sql Server數據庫時將數據類型nvarchar轉換爲數字時出錯
當我選擇幾個專欄中,我得到這個錯誤
private static void ImportToSql(string ssqlconnectionstring, string query)
{
string query = "MERGE Inventory AS target USING (select LocalSKU,ItemName, QOH,ISNULL(Price,0.00),Discontinued,Integer2,Integer3 from @source) as source ON (source.LocalSKU = target.LocalSKU) WHEN MATCHED THEN UPDATE SET ItemName=source.ItemName,Price=source.Price,Discontinued=source.Discontinued,Integer2=source.Integer2,Integer3=source.QOH;";
string excelfilepath = Environment.CurrentDirectory + @"\Sheet1.csv";
// make sure your sheet name is correct, here sheet name is sheet1, so you can change your sheet name if have different
// string myexceldataquery = "select LocalSKU,ItemName,QOH,Price,Discontinued,Barcode,Integer2,Integer3,SalePrice,SaleOn,Price2 from [sheet1$]";
string myexceldataquery = "select LocalSKU,ItemName, QOH,Price,Discontinued,Integer2,Integer3 from [sheet1$]";
try
{
// string sexcelconnectionstring = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + excelfilepath + ";Extended Properties=Excel 12.0;";
string sexcelconnectionstring = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source =" + excelfilepath + "; Extended Properties=\"Excel 12.0; HDR=Yes; IMEX=2; ImportMixedTypes=Text;\"";
//string ssqlconnectionstring = "Data Source=User-PC\\Dell;Trusted_Connection=True;DATABASE=TestStore;CONNECTION RESET=FALSE";
SqlConnection sqlconn = new SqlConnection(ssqlconnectionstring);
//series of commands to bulk copy data from the excel file into our sql table
OleDbConnection oledbconn = new OleDbConnection(sexcelconnectionstring);
OleDbCommand oledbcmd = new OleDbCommand(myexceldataquery, oledbconn);
oledbconn.Open();
OleDbDataReader dr = oledbcmd.ExecuteReader();
SqlCommand sqlcmd = new SqlCommand(@query, sqlconn);
SqlParameter param;
param = sqlcmd.Parameters.AddWithValue("@source", dr);
param.SqlDbType = SqlDbType.Structured;
param.TypeName = "dbo.DTTOW";
sqlconn.Open();
sqlcmd.ExecuteNonQuery();
sqlconn.Close();
oledbconn.Close();
Console.WriteLine(".xlsx file imported succssessfully into database. /r /n ");
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
此代碼的工作。 「」將數據類型nvarchar轉換爲數字時出錯。
我使用用戶定義的數據類型:
CREATE TYPE [dbo].[DTTOW] AS TABLE(
[LocalSKU] [varchar](200) NOT NULL,
[ItemName] [varchar](200) NULL,
[QOH] [int] NULL,
[Price] [decimal](19, 4) NULL,
[Discontinued] [bit] NULL,
[Integer2] [int] NULL,
[Integer3] [int] NULL
)
你有什麼,在Excel中價格列非數字值替換非數值?任何與空格,字母,null或空字符串? –
是的..有你的觀點..你能吸引我如何處理這些..? – user3590485
我發佈了一個答案哦,如何處理它們。 –