如何使用C#将Excel工作表中的数据插入SQL Server

时间:2015-04-29 07:32:17

标签: c# sql-server excel

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

这段代码效果很好,但我想存储除二进制图像之外的大量数据,如ID,图片网址,图片名称。

任何人都可以帮助我吗?

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

1 个答案:

答案 0 :(得分:0)

表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]