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

本文介绍如何使用C#从Excel中提取图片,将其转换为字节流并存储到数据库中,同时展示了如何创建目录、读取图片文件和执行SQL插入操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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);
            }
        }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值