我有一个Excel表格,其中包含35,000个产品图像的URL。我正在寻找从url下载图像的方法,然后我可以将它们作为映像插入到Server中。我不知道我需要帮忙。
有什么想法吗?
发布于 2015-04-25 11:19:11
我会尝试在一个独立的程序中做类似的事情,例如命令行实用程序或者什么的。我用C#编写了这个代码,不管出于什么原因,在线的C#到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,添加更多的日志记录(对于成功的案例等等)--但这应该是这个小程序的粗略框架。
https://stackoverflow.com/questions/29863485
复制相似问题