Skip to main content
 首页 » 编程设计

c#之使用 C# 和 asp.net 将 CSV 文件导入 SQL

2024年02月06日11emanlee

我正在使用 SQL Server 2014。我的 Web 应用程序的一个功能是上传 CSV 文件,并将数据导入到我的数据库(名为 TMPA).

我不知道该怎么做。

string excelPath = Server.MapPath("~/Files/") + Path.GetFileName(FileUpload2.PostedFile.FileName); 
FileUpload1.SaveAs(excelPath); 
 
SqlConnection con = new SqlConnection(@"Data Source=SAMSUNG-PC\SQLEXPRESS;Initial Catalog=TMPA;Persist Security Info=True"); 
 
StreamReader sr = new StreamReader(excelPath); 
string line = sr.ReadLine(); 
string[] value = line.Split(','); 
 
DataTable dt = new DataTable(); 
DataRow row; 
 
foreach (string dc in value) 
{ 
    dt.Columns.Add(new DataColumn(dc)); 
} 
 
while (!sr.EndOfStream) 
{ 
   value = sr.ReadLine().Split(','); 
 
   if (value.Length == dt.Columns.Count) 
   { 
      row = dt.NewRow(); 
      row.ItemArray = value; 
      dt.Rows.Add(row); 
   } 
} 
 
SqlBulkCopy bc = new SqlBulkCopy(con.ConnectionString, SqlBulkCopyOptions.TableLock); 
bc.DestinationTableName = "TF"; 
bc.BatchSize = dt.Rows.Count; 
 
con.Open(); 
bc.WriteToServer(dt); 
bc.Close(); 
 
con.Close(); 

我试过这段代码,但行不通。

PS:TF 的列比 CSV 文件的列多:有些列是计算出来的,应该在每次插入后自动计算..

这是我的 CSV 文件的 Canvas :4 列:

 IdProduit,Mois,Reel,Budget 

IdProduit 是字符串,Mois 是日期,Reel 和 Budget 是 float 。

另一方面,我的 SQL Server 表如下所示:

  |IdProduit|Mois|Reel|Budget|ReelPreviousMois|VarReelBudget|VarReelPrvM|... 
  |---------|----|----|------|----------------|-------------|-----------|----- 

所有其他列应该为空或自动计算。

帮帮我!

请您参考如下方法:

我使用这个名为 Filehelpers 的开源 .net 库修复了它。 这是链接:http://www.filehelpers.net/

这是我做的:

 <asp:FileUpload ID="FileUpload1" runat="server" /> 
        <asp:Button ID="Button1" OnClick = "UploadF" runat="server" Text="Importer" /> 

下面是代码:

    [DelimitedRecord("|")] 
    public class TBFtable  
{  
    public string IdProduit;  
    public DateTime Mois;  
    public float Reel;  
    public float Budget;  
 
}  
 
    protected void UploadF(object sender, EventArgs e) 
 
    { 
 
        string excelPath = Server.MapPath("~/Files/") + Path.GetFileName(FileUpload1.PostedFile.FileName); 
        FileUpload1.SaveAs(excelPath); 
 
        SqlServerStorage storage = new SqlServerStorage(typeof(TBFtable),ConfigurationManager.ConnectionStrings["bd"].ConnectionString); 
 
 
         storage.InsertSqlCallback = new InsertSqlHandler(GetInsertSqlCust); 
 
        TBFtable[] res = CommonEngine.ReadFile(typeof(TBFtable), excelPath) as TBFtable[];  
        storage.InsertRecords(res); 
        ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alertMessage", "alert('Données enregistrées avec succès !')", true); 
    } 
 
    protected string GetInsertSqlCust(object record)  
{  
    TBFtable obj = (TBFtable) record;  
 
    return String.Format("INSERT INTO TF (IdProduit, Mois, Reel, Budget ) " +  " VALUES ( '{0}' , '{1}' , '{2}' , '{3}'  ); ", obj.IdProduit, obj.Mois,obj.Reel, obj.Budget );  
 
}