2016-11-29 29 views
1
public DataTable InsertToIncludeandReturnErrorTable(DataTable MappingTable, DataTable InsertTable, string TableName) 
{ 
    //split data and insert data to datatable and validation 
    var CS = Serenity.Data.SqlConnections.GetConnectionString("Northwind"); 
    String MyConString = CS.ConnectionString; 
    SqlConnection con = new SqlConnection(); 
    con.ConnectionString = MyConString; 
    DataTable returnDataTable = InsertTable.Clone(); 
    con.Open(); 
    foreach (DataRow InsertRow in InsertTable.Rows) 
    { 
     try 
     { 
      string InsertDBFileld = ""; 
      string DatarowField = ""; 

      foreach (DataRow row in MappingTable.Rows) 
      { 
       if (InsertDBFileld == "") 
        InsertDBFileld = InsertDBFileld + row["TableColumn"].ToString().Replace("\r\n", ""); 
       else 
        InsertDBFileld = InsertDBFileld + "," + row["TableColumn"].ToString().Replace("\r\n", ""); 

       if (DatarowField == "") 
        DatarowField = "'" + DatarowField + InsertRow[row["ExcelColumn"].ToString().Replace("\r\n", "")].ToString() + "'"; 
       else 
        DatarowField = DatarowField + ",'" + InsertRow[row["ExcelColumn"].ToString().Replace("\r\n", "")].ToString() + "'"; 
      } 
      InsertDBFileld = InsertDBFileld + @",CreatedBy,CreatedDate,ModifiedBy,ModifiedDate"; 
      DatarowField = DatarowField + ",'" + User.Identity.Name + "'," + "'" + DateTime.Now + "'," + "'" + User.Identity.Name + "'," + "'" + DateTime.Now + "'"; 

      using (SqlCommand cmd = new SqlCommand(@"INSERT INTO dbo." + TableName + @"(
                " + InsertDBFileld + @" 
                ) VALUES(" + DatarowField + ")", con)) 
      { 

       cmd.ExecuteNonQuery(); 

      } 


     } 
     catch (Exception ex) 
     { 
      DataRow returnRow = InsertRow; 
      returnDataTable.Rows.Add(InsertRow.ItemArray); 
     } 
    } 
    if (con.State == System.Data.ConnectionState.Open) 
     con.Close(); 
    return returnDataTable; 

} 
[HttpGet] 
public FileContentResult DownLoadFile(string destFilePath) 
{ 
    //Generate Excel file with data 
    destFilePath = destFilePath.Replace("%5c", "\\").Replace("%3a", ":"); 
    byte[] fileBytes = System.IO.File.ReadAllBytes(destFilePath); 
    string fileName = "ErrorList.xlsx"; 
    return File(fileBytes, System.Net.Mime.MediaTypeNames.Application.Octet, fileName); 

} 

元号は、列データの長さを検出して間違ったデータ行を出力できます。c#列のデータ型とサイズを取得

どのようにしてデータ型と列のサイズを取得できますか?

データの長さを超えてExcelをアップロードした場合、Excelファイルを出力して間違ったデータセルに赤い色を入力してください。

+0

SQLに付属のSQL Server Management Studioを使用し、エクスプローラを使用してデータベースとテーブルを検索します。次に列を見てください。 – jdweng

答えて

1

あなたDataTableの列からのデータの種類と最大長さを確認することができます。

Type columnType = InsertTable.Columns["TableColumn"].DataType; 
int maxLength = InsertTable.Columns["TableColumn"].MaxLength; 

あなたのテーブルには、(私は疑う)スキーマ情報が含まれていない場合は、データベースからの最初のスキーマを取得することができますSqlDataAdapterである。 FillSchemaメソッドが必要です。

関連する問題