简体   繁体   中英

How can I insert data from Excel sheet into SQL Server using C#

I have this pretty code for import URL's from Excel and download images to store them in SQL Server in a varbinary(max) column.

This code works very well, but I want to store a lot of data like ID, image url, image name besides the binary images.

Can anyone help me with that?

// 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
          }
     }
}

Table SQl server looks like that

    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]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM