显示自定义错误消息,如果数据types不匹配时,将excel文件读入数据库(在C#程序中)
我是新来的.NET,希望得到我的下面的场景一些build议:
情景:我有一个外部Excel文件,应该读取并使用C#加载到数据库中。
所以,为此我创build了两个表格:
-
临时表(在加载到最终表之前,从Excel文件中读取数据的临时表)。
-
最终表(包含validation的数据)。 在临时表中,我需要编写一个程序来validation数据types,并通过显示错误消息来提示用户(例如:excel列只包含数值,如果任何单元格包含该特定列中的文本/string,C#程序应显示消息(“文本不允许,请input数值”)。
为了达到上述目的,我想编写一个将临时表存储错误信息的存储过程,C#程序执行存储过程来读取临时表中的错误信息。
我通过将非数字/文本(“ABC”)值赋予数字列来尝试上述过程。 但是我没有收到一个错误信息,因为它是空的,而不是显示错误信息
OLEDB连接string:
string STR_OLEDBCONNECTION = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source='" + PATH + "';Extended Properties='Excel 12.0 Xml;HDR=Yes';IMEX = 1";
下面是SQL存储过程将错误消息读入临时表。
USE [EXCEL_DATABASE] GO CREATE PROCEDURE [dbo].[spexcel] AS BEGIN --SET NOCOUNT ON added to prevent extra result sets from --interfering with SELECT statements. SET NOCOUNT ON; DECLARE @count int IF OBJECT_ID('tempdb..#TempResult') IS NOT NULL DROP TABLE #TempResult CREATE TABLE #TempResult ( [Messages] nvarchar(max) NULL ) --Incremental Table 1 INSERT INTO #TempResult SELECT '[Incremental File 1] Column [Units] at Row: ' + CONVERT(nvarchar(255),(SCOPE_IDENTITY() + 1)) + ' is not in correct date format' FROM [dbo].[Staging_OEM] WHERE [Units] IS NOT NULL AND TRY_CONVERT(float, [Units]) IS NULL SELECT @count = COUNT(*) FROM #TempResult IF @count = 0 BEGIN INSERT INTO [dbo].[Final_OEM] ([Source], [Geography], [Product Type], [Period], [Period Format],[Year], [Device Type], [Segment Type], [Platform], [Units],[Other Software Units],[Revenue],[Budget Units],[Budget Revenue],[Hardware Units],[Brand],[Price Band],[Segment],[Prod Rollup]) SELECT [Source], [Geography], [Product Type], [Period], [Period Format],[Year], [Device Type], [Segment Type], [Platform],CONVERT(float, [Units]),[Other Software Units],CONVERT(float,[Revenue]),CONVERT(float,[Budget Units]),CONVERT(float,[Budget Revenue]),[Hardware Units],[Brand],[Price Band],[Segment],[Prod Rollup] FROM [dbo].[Staging_OEM] END SELECT * FROM #TempResult END
C#程序来读取临时表消息:
static bool checkNumeric(SqlConnection SQLConnection,string fileLabel) { bool result = true; var errMsg = ""; using (SqlCommand cmd = new SqlCommand()) { cmd.CommandText = "[EXCEL_DATABASE].[dbo].[spExcel]"; cmd.CommandType = CommandType.StoredProcedure; cmd.Connection = SQLConnection; SqlDataReader reader = cmd.ExecuteReader(); while (reader.Read()) { errMsg += reader[0].ToString() + Environment.NewLine; } cmd.Dispose(); reader.Close(); } if (errMsg != "") { Common.writeToError("[" + DateTime.Now.ToString() + "] Error encountered while reading " + fileLabel + Environment.NewLine + errMsg); result = false; } else { Common.writeToLog("[" + DateTime.Now.ToString() + "] Reading " + fileLabel + " is successful."); } return result; } } }