【问题标题】:Import image from Excel sheet into SQL Server table C#将 Excel 工作表中的图像导入 SQL Server 表 C#
【发布时间】:2013-09-29 04:48:33
【问题描述】:

在这里,我想使用 C# 代码将我的 excel 表中的所有数据插入到 SQL Server 表中

我有这样的数据的 Excel 表

ID    Name    Designation    ProfilePicture
--------------------------------------------
1    ABC      Manager        C:\Pictures\1.jpg
2    DEF      Asst.Manager   C:\Pictures\2.jpg

我有将数据插入表格的代码

String filePath = filePathText.Text;
String fileExtension = "Excel 12.0";
if (filePath != null)
{
    String xlsConnection = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filePath + ";Extended Properties=" + "\"" + fileExtension + ";HDR=YES;\"";

    String sqlConnection = "Your Connection String";

    //Connection to Excel work book
    OleDbConnection xlsConnectionString = new OleDbConnection(xlsConnection);

    //Fetch data from Excel
    OleDbCommand cmd = new OleDbCommand("Select [ID],[Name],[Designation],[ProfilePicture] from [Sheet1$]", xlsConnectionString);

    xlsConnectionString.Open();

    OleDbDataReader dReader;
    dReader = cmd.ExecuteReader();
    SqlBulkCopy sqlBulk = new SqlBulkCopy(sqlConnection);

    //Destination table name
    sqlBulk.DestinationTableName = "EXCEL_DATA";

    sqlBulk.WriteToServer(dReader);

    xlsConnectionString.Close();
}

如果我点击按钮,这段代码就会运行。

我的问题是,如何从 Excel 表格上传图片(表格有图像的路径)。到SQL Server 表。我想通过使用 Excel Sheet 中提供的 Imagepath 来获取图片并将其存储为 varbinary(MAX)SQL Server 中。

【问题讨论】:

    标签: c# sql-server excel


    【解决方案1】:

    感谢那些真正努力发布答案的人。终于我自己解决了问题。

    这是帮助使用Excel sheet 中提供的路径将图像插入SQL Server 的代码。

        private void insert_Click(object sender, EventArgs e)
        {
    
            UInt64 ID = 0;
            String Name = String.Empty;
            String Designation = String.Empty;
            String ProfilePicture = String.Empty;
    
            String filePath = filePathText.Text;
    
            Excel.Application xlApp = null;
            Excel.Workbook xlWorkbook = null;
            Excel._Worksheet xlWorksheet = null;
            Excel.Range xlRange = null;
    
            String sqlConnectionString = "Your Connection String goes here";
    
            String insertRecord = "INSERT_USER_RECORDS";
    
            SqlConnection sqlConnection = new SqlConnection(sqlConnectionString);
            SqlCommand sqlCommand = new SqlCommand(insertRecord, sqlConnection);
            sqlCommand.CommandType = CommandType.StoredProcedure;
    
            sqlConnection.Open();
    
            if (filePath != null)
            {
    
                try
                {
    
                    xlApp = new Excel.Application();
                    xlWorkbook = xlApp.Workbooks.Open(filePath);
                    xlWorksheet = (Excel._Worksheet)xlWorkbook.Sheets[1];
                    xlRange = xlWorksheet.UsedRange;
    
                    int rowCount = xlRange.Rows.Count;
                    int colCount = xlRange.Columns.Count;
    
                    for (int row = 1; row <= rowCount; row++)
                    {
                        for (int col = 1; col <= colCount; col++)
                        {
                            MessageBox.Show((xlRange.Cells[row, col] as Microsoft.Office.Interop.Excel.Range).Value2.ToString());
    
                            // Check xlRange for Every run. And assign values to local variables. Here I just show the values using MsgBox
    
                            // If you get the Path of Image then call the function to Convert Image into byte
    
                            // Convert Image to Byte Function definition.
    
                            /* System.IO.FileStream fs = new System.IO.FileStream(ProfilePicture, System.IO.FileMode.Open);
                               Byte[] imageAsBytes = new Byte[fs.Length];
                               fs.Read(imageAsBytes, 0, imageAsBytes.Length);
                               fs.Close();
                               return imageAsBytes; */
    
                        }
    
                        sqlCommand.Parameters.Clear();
                        sqlCommand.Parameters.Add("@Name", SqlDbType.NVarChar).Value = FirstName;
                        sqlCommand.Parameters.Add("@Designation", SqlDbType.NVarChar).Value = LastName;
                        sqlCommand.Parameters.Add("@ProfilePicture", SqlDbType.VarBinary).Value = imageAsBytes;
                        sqlCommand.Parameters.Add("@ID", SqlDbType.BigInt).Value = ID;
    
                        sqlCommand.ExecuteNonQuery();
                    }
    
    
                    MessageBox.Show(Path.GetFileName(filePath) + "is Successfully imported to SQL Server", "Result", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, "Exception", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                finally
                {
                    //Release All objects and close the Connection to prevent the Excel file from lock.
    
                    sqlConnection.Close();
    
                    GC.Collect();
                    GC.WaitForPendingFinalizers();
    
                    Marshal.FinalReleaseComObject(xlRange);
                    Marshal.FinalReleaseComObject(xlWorksheet);
    
                    xlWorkbook.Close(Type.Missing, Type.Missing, Type.Missing);
                    Marshal.FinalReleaseComObject(xlWorkbook);
    
                    xlApp.Quit();
                    Marshal.FinalReleaseComObject(xlApp);
    
                }
            }
            else
            {
                MessageBox.Show("Please Select the Valid file to import");
            }
        }
    

    此代码运行良好,可帮助我将图像从 Excel 插入到 SQL 数据库中。 与excel文件的版本无关。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-12-05
      • 1970-01-01
      • 2012-09-14
      • 1970-01-01
      • 2021-11-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多