我有一张Excel表格,其中包含35,000个产品图片的网址。 我正在寻找一种从url下载图像的方法 之后我可以将它们作为图像插入SQL Server。 我不知道我需要帮忙。
有什么想法吗?
答案 0 :(得分:1)
我会尝试在独立程序中执行类似的操作 - 例如命令行实用程序或其他东西。我用C#编写了这个,无论出于何种原因,在线C#-to-VB.NET转换器都被禁止并且无法转换 - 我希望你能得到基本的想法,你可以自己在VB.NET中做到这一点。
第一步:让ExcelDataReader读取Excel文件。
然后做这样的事情:
// 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
}
}
}
这应该可以满足您的需求 - 当然,您还可以做很多额外的事情 - 只从Excel文件中读取一定数量的URL,添加更多日志记录(也适用于成功案例等) - 但是这应该是这个小程序的粗略骨架