【问题标题】:How can I insert data from Excel sheet into SQL Server using C#如何使用 C# 将 Excel 工作表中的数据插入 SQL Server
【发布时间】:2015-04-29 07:32:16
【问题描述】:

我有这个漂亮的代码,用于从 Excel 导入 URL 并下载图像以将它们存储在 SQL Server 中的 varbinary(max) 列中。

这段代码效果很好,但是除了二进制图像之外,我还想存储很多数据,例如 ID、图像 url、图像名称。

谁能帮我解决这个问题?

// define list of URLs
List<string> imageUrls = new List<string>();

// open Excel file and read in the URLs into a list of strings
string filePath = @"C:\YourUrlDataFile.xlsx";  // adapt to YOUR needs!

// using a "FileStream" and the "ExcelDataReader", read all the URL's
// into a list of strings
using (FileStream stream = File.Open(filePath, FileMode.Open, FileAccess.Read))
{
    using (IExcelDataReader excelReader = ExcelReaderFactory.CreateOpenXmlReader(stream))
    {
        while (excelReader.Read())
        {
            string url = excelReader.GetString(0);
            imageUrls.Add(url);
        }

        excelReader.Close();
    }
}

// set up the necessary infrastructure for storing into SQL Server
// the query needs to be *ADAPTED* to your own situation - use *YOUR* 
// table and column name!
string query = "INSERT INTO dbo.TestImages(ImageData) VALUES(@Image);";

// get the connection string from config - again: *ADAPT* to your situation!
string connectionString = ConfigurationManager.ConnectionStrings["YourDatabase"].ConnectionString;

// use SqlConnection and SqlCommand in using blocks
using(SqlConnection conn = new SqlConnection(connectionString))
using (SqlCommand cmd = new SqlCommand(query, conn))
{
    // add parameter to SQL query
    cmd.Parameters.Add("@Image", SqlDbType.VarBinary, -1);

    // loop through the URL's - try to fetch the image, 
    // and if successful, insert into SQL Server database
    foreach (string url in imageUrls)
    {
         try
         {
              // get a new "WebClient", and fetch the data from the URL
              WebClient client = new WebClient();
              byte[] imageData = client.DownloadData(url);

              // open connection
              conn.Open();

              // set the parameter to the data fetched from the URL
              cmd.Parameters["@Image"].Value = imageData;

              // execute SQL query - the return value is the number
              // of rows inserted - should be *1* (if successful)
              int inserted = cmd.ExecuteNonQuery();

              // close connection
              conn.Close();
          }
          catch (Exception exc)
          {
              // Log the exception
          }
     }
}

【问题讨论】:

  • ID 等这些东西是否也存储在您的 Excel 工作表中?您的目标 SQL Server 表是什么样的(列名、数据类型)?
  • 使用excelReader.GetString(index); 其中index 是从中读取数据的列,我认为这就是你想要的
  • 您的问题到底是什么?什么问题是你想不出来解决的?必须采取什么措施来实现这一目标,还是您要求我们完成您的工作?
  • 我做不到,所以我请求帮助完成我的工作!!!我把正确的代码你要我把我的错误代码放在这里这就是你的意思؟我尝试了 2 天,但我失败了@Patrik Eckebrecht
  • 我只想知道如何使用上面的 C# 代码添加一种整数或 varchar 字段。添加其他人就足够了。

标签: c# sql-server excel


【解决方案1】:

Table SQl 服务器看起来像这样

    CREATE TABLE [dbo].[inv](
    [id] [bigint] NOT NULL,
    [upc] [bigint] NULL,
    [item_spec] [nvarchar](300) NULL,
    [quantity] [int] NULL,
    [original_cost] [money] NULL,
    [total_o_cost] [money] NULL,
    [retail_price_usd] [money] NULL,
    [total_o_retail] [money] NULL,
    [vendor_style] [nvarchar](255) NULL,
    [colors_id] [int] NULL,
    [size_id] [int] NULL,
    [client_cost_usd] [money] NULL,
    [total_client_cost] [money] NULL,
    [div_id] [int] NOT NULL,
    [depart_id] [int] NOT NULL,
    [vendor_id] [int] NOT NULL,
    [image] [varbinary](max) NULL,
    [image_id] [int] NULL,
    [location_id] [int] NULL,
    [id_lot_number] [int] NULL,
    [lot_number] [int] NULL,
    [bol] [float] NULL,
    [categories_id] [int] NOT NULL,
    [return_id] [int] NULL,
    [of_pallets] [float] NULL,
    [of_cartons] [float] NULL,
    [season_id] [int] NULL,
    [hs_code] [int] NULL,
    [sales_price] [money] NULL,
    [brand_id] [int] NOT NULL,
    [sku] [int] NULL,
    [barcode] [nvarchar](255) NULL,
    [sar] [money] NULL,
    [aed] [money] NULL,
    [bhd] [money] NULL,
 CONSTRAINT [PK_inv] PRIMARY KEY CLUSTERED 
(
    [id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

【讨论】:

    猜你喜欢
    • 2012-11-23
    • 2017-02-21
    • 1970-01-01
    • 1970-01-01
    • 2012-09-14
    • 1970-01-01
    • 1970-01-01
    • 2014-09-13
    • 1970-01-01
    相关资源
    最近更新 更多