【发布时间】: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