c#读取excel表格中图片并且存入数据库

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using Spire.Xls;
using System.IO;
using System.Drawing;
public void xlzs()
        {
    
    
            string activeDir = System.AppDomain.CurrentDomain.BaseDirectory;
            string newPath = System.IO.Path.Combine(activeDir, "images");
            System.IO.Directory.CreateDirectory(newPath);
            //获取当前路径并且创造一个images文件
            Workbook wb = new Workbook();
            wb.LoadFromFile("D:/exc/b1.xls");
             //获取第一个工作表
            Worksheet sheet = wb.Worksheets[0];
            //获取工作表中的第一张图片
            ExcelPicture picture = sheet.Pictures[0];
            //保存图片到images文件下
            picture.Picture.Save(newPath + "/ExtractedImg.png");
            //System.Diagnostics.Process.Start("D:/exc/ExtractedImg.png");
            string connStr = System.Configuration.ConfigurationManager.AppSettings["oasys"].ToString();
            SqlConnection sqlConnection2 = new SqlConnection(connStr);
            sqlConnection2.Open();
            //打开数据web.config中的数据库
            string dz = newPath + "/ExtractedImg.png";
            byte[] im = GetPictureData(dz);
            //把图片转变为数据流
            string sql = "insert into xlzs(sfz,xl_image) values ('222','@Image')";
            SqlCommand sqlCommand11 = new SqlCommand(sql, sqlConnection2);
            //建立sql语句是与打开数据库的链接
            sqlCommand11.Parameters.Add("@Image", SqlDbType.Image);
            sqlCommand11.Parameters["@Image"].Value = im;//赋值
            sqlCommand11.ExecuteNonQuery();
            //执行sql语句
            sqlConnection2.Close();// Response.Write("a");
            DeleteImgFile(newPath + "/ExtractedImg.png");
            //删除之前保存的图片 }
 
  public byte[] GetPictureData(string imagepath)//根据图片文件的路径使用文件流打开,并保存为byte[] 
        {
    
    
            /**/
            
            FileStream fs = new FileStream(imagepath, FileMode.Open);//可以是其他重载方法 
            byte[] byData = new byte[fs.Length];
            fs.Read(byData, 0, byData.Length);
            fs.Close();
            return byData;
        }
       public static void DeleteImgFile(string fileUrl)//删除文件中的图片
        {
    
    
            
            if (System.IO.File.Exists(fileUrl))
            {
    
    
                System.IO.File.Delete(fileUrl);
            }
        }

猜你喜欢

转载自blog.csdn.net/qq_44162236/article/details/105929614