首页 > 编程语言 >使用net core 6 c# 的 NPOI 包,读取excel..xlsx单元格内的图片 和悬浮的图片,并存储到指定服务器

使用net core 6 c# 的 NPOI 包,读取excel..xlsx单元格内的图片 和悬浮的图片,并存储到指定服务器

时间:2024-02-04 14:49:14浏览次数:26  
标签:core return string .. mapPath var path null 图片

抄的两个前辈的代码,反正是实现了
https://www.cnblogs.com/IT-Ramon/p/13100039.html
https://www.cnblogs.com/zhaocici/p/16434320.html
合并了两个代码的功能,反正能用
他们是在web上用,我是在桌面程序上用,小改一下就可以用了

点击查看代码
using ICSharpCode.SharpZipLib.Zip;
//using Microsoft.AspNetCore.Mvc;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using System.Collections.Generic;
using System;
using System.Data;
using System.Data.Entity.Core.Common.CommandTrees.ExpressionBuilder;
using System.IO;
using System.Runtime.InteropServices;
using System.Xml;
using System.Linq;
using NPOI.OpenXmlFormats.Dml.Diagram;
using System.Windows.Forms;
using System.Threading.Tasks;
using NPOI.SS.Formula.Functions;

namespace ExcelOption.Controllers
{
    //[ApiController]
    //[Route("[controller]")]
    public class ImportExcelController 
    {

        //private readonly Microsoft.AspNetCore.Hosting.IHostingEnvironment _hostingEnvironment;

        //public ImportExcelController(Microsoft.AspNetCore.Hosting.IHostingEnvironment hostingEnvironment)
        //{
        //    _hostingEnvironment = hostingEnvironment;
        //}

        //[HttpGet(Name = "dele")]
        public bool dele()
        {
            string zipFileName = "filezip" + ".zip";
            string xlsxFileName = "filexlsx" + ".xlsx";
            var mapPath = Path.Combine(Application.StartupPath, "img");
            //业务逻辑处理完了就把原来的文件和解压的文件夹删除
            Directory.Delete(mapPath + @"\" + "filezip", true);
            System.IO.File.Delete(mapPath + @"\" + xlsxFileName);
            //File.Delete(mapPath + "\\" + xlsxFileName);
            System.IO.File.Delete(mapPath + @"\" + zipFileName);

            return true;
        }

        //[HttpPost(Name = "ImportExcel_Img")]
        public  void ImportExcel_Img(string filename)
        {

          //  if (files.Count > 0)
            {
                var file = new FileStream(filename, FileMode.Open, FileAccess.Read);
                //读取导入的文件类型
                var fileExt = Path.GetExtension(filename).ToLower();
                if (!fileExt.Equals(".xlsx"))
                {
                    //提示文件类型不正确
                  //  return false;
                }
                //转换保存zip
                string zipFileName = "filezip" + ".zip";
                string xlsxFileName = "filexlsx" + ".xlsx";
                var mapPath = Path.Combine(Application.StartupPath, "imgs\\");
                //保存xlsx到目录下
                if (!Directory.Exists(mapPath)) { Directory.CreateDirectory(mapPath); }
                //判断文件是否存在
                if (File.Exists(mapPath + xlsxFileName)) { File.Delete(mapPath + xlsxFileName); }

                 Task.Run(() => File.Copy(filename, mapPath + xlsxFileName));

                //using (var stream = new FileStream(mapPath + xlsxFileName, FileMode.OpenOrCreate, FileAccess.ReadWrite))
                //{
                //    await file.CopyToAsync(stream);

                //}

                //保存zip到服务器
                //查看文件是否存在
                if (File.Exists(mapPath + zipFileName)) { File.Delete(mapPath + zipFileName); }
                Task.Run(() => File.Copy(filename, mapPath + zipFileName));

                //using (var stream = new FileStream(mapPath + zipFileName, FileMode.OpenOrCreate, FileAccess.ReadWrite))
                //{
                //    await file.CopyToAsync(stream);
                //}
                var dt = ExcelHelper.ExcelToDataTable(mapPath + xlsxFileName);
                if (dt == null) { return; }
                    foreach (DataRow row in dt.Rows.Cast<DataRow>().ToList())
                {
                    //判断行是否为空
                    if (IsRowEmpty(row))
                    {
                        dt.Rows.Remove(row);
                    }
                }
               
                
                //解压,如果解压成功则根据xml处理 (应为方便我就放在ExcelHelper里面了)
                if (UnZipFile(mapPath + zipFileName, out string path))
                {
                    //excel 图片信息
                    List<o_ExcelImgModel> o_ExcelImgModelList = new List<o_ExcelImgModel>();
                    List<o_ExcelImgModel> o_ExcelImgModelListFloat = new List<o_ExcelImgModel>();
                    //图片路径文件夹
                    var mediaFolderPath = path + @"xl\media";
                    //判断是否存在此文件夹如果有则处理(如果没有图片他是不会有这个文件夹的)
                    if (System.IO.Directory.Exists(mediaFolderPath))
                    {
                        //解压成功获取xml 节点做处理
                        var exclNode = GetXmlExclNodeList(path);
                        var pictNode = GetXmlPictNodeList(path);
                        var exclNodefloat = GetXmlExclNodeListFloat(path);
                        var pictNodefloat = GetXmlPictNodeListFloat(path);
                        //获取嵌入图片信息与地址
                        foreach (var nl in exclNode)
                        {
                            XmlElement sondNode = (XmlElement)nl;
                            XmlNodeList descendDodeList = sondNode.ChildNodes;
                            XmlNodeList picNodeList = descendDodeList[0].ChildNodes;


                            XmlNodeList nvPicPrNodeList = picNodeList[0].ChildNodes;
                            XmlElement cNvPrElement = (XmlElement)nvPicPrNodeList.Item(0);
                            string name = cNvPrElement.GetAttribute("name").ToString();


                            XmlNodeList blipFillNodeList = picNodeList[1].ChildNodes;
                            XmlElement picElement = (XmlElement)blipFillNodeList.Item(0);
                            string id = picElement.GetAttribute("r:embed").ToString();


                            foreach (XmlNode xn in pictNode)
                            {
                                XmlElement xe = (XmlElement)xn;
                                if (xe.GetAttribute("Id").ToString() == id)
                                {
                                    var pathOfPicture = xe.GetAttribute("Target").ToString().Replace("..", "").Replace("/", @"\");
                                    pathOfPicture = path + @"xl\" + pathOfPicture;
                                    o_ExcelImgModelList.Add(new o_ExcelImgModel()
                                    {
                                        ID = id,
                                        Name = name,
                                        PathOfPicture = pathOfPicture
                                    });
                                    break;
                                }
                            }
                        }
                        //图片对应dt的哪一列,存到dt然后再循环dt去处理(这个是小编的思维,如果有更好的做法可以随缘发挥)
                        foreach (var item in o_ExcelImgModelList)
                        {
                            //item.PathOfPicture  图片路径取到了,此时你可以存储了
                            Console.WriteLine(item.PathOfPicture);
                        }

                        //获取悬浮图片信息与地址
                        foreach (var nl in exclNodefloat)
                        {
                            XmlElement sondNode = (XmlElement)nl;

                            XmlNodeList descendDodeList = sondNode.ChildNodes;

                            XmlNodeList fromNodeList = descendDodeList[0].ChildNodes;

                            //取得行号

                            var row = Convert.ToInt32(fromNodeList.Item(2).InnerText.Trim());

                            var col = Convert.ToInt32(fromNodeList.Item(0).InnerText.Trim());

                            XmlNodeList picNodeList = descendDodeList[2].ChildNodes;

                            XmlNodeList blipFillNodeList = picNodeList[1].ChildNodes;

                            XmlElement picElement = (XmlElement)blipFillNodeList.Item(0);

                            string id = picElement.GetAttribute("r:embed").ToString();

                            foreach (XmlNode xn in pictNodefloat)
                            {

                                XmlElement xe = (XmlElement)xn;
                                if (xe.GetAttribute("Id").ToString() == id)
                                {
                                    var pathOfPicture = xe.GetAttribute("Target").ToString().Replace("..", "").Replace("/", @"\");

                                    pathOfPicture = path + "\\xl" + pathOfPicture;
                                    o_ExcelImgModelListFloat.Add(new o_ExcelImgModel()
                                    {
                                        ID = id,
                                        Col = col,
                                        Row = row,
                                        PathOfPicture = pathOfPicture
                                    });

                                    break;
                                }
                            }
                        }
                        //图片对应dt的哪一列,存到dt然后再循环dt去处理(这个是小编的思维,如果有更好的做法可以随缘发挥)
                        foreach (var item in o_ExcelImgModelListFloat)
                        {
                            dt.Rows[item.Row - 1][item.Col] += string.IsNullOrWhiteSpace(dt.Rows[item.Row - 1][item.Col].ToString()) ? item.PathOfPicture : "," + item.PathOfPicture;
                        }



                    }
                    //现在dt某一列存放了图片的绝对路径就可以通过table去处理了
                    //循环表插入数据及上传
                    foreach (DataRow item in dt.Rows)
                    {


                        //此时你excel转换的 dataTable表的图片字段的 值是:"_xlfn.DISPIMG(\"ID_CD49305586E940EF8F78CD3B54A4BCD3\",1)"
                        Console.WriteLine(item["fbanum"].ToString());  //"zhao1"

                        //var kkl= item["IMG"].ToString(); //  "_xlfn.DISPIMG(\"ID_CD49305586E940EF8F78CD3B54A4BCD3\",1)"

                        Console.WriteLine(item["图片"].ToString());
                        var itmevalue = item["图片"].ToString();
                        if (itmevalue.Contains("_xlfn")) { 
                            var breakApart = item["图片"].ToString().Split('\\', '"')[1];
                            var imgPath = o_ExcelImgModelList.FirstOrDefault(x => x.Name == breakApart);
                        
                            item["图片"] = imgPath.PathOfPicture;
                            //dt.Rows[]
                        }

                        //获取图片然后做上传逻辑,这个自己实现我就不多讲了
                    }
                }
                else
                {
                    //解压时报直接返回,这个返回啥类型或者啥数据自己定义就好我这边demo 随缘来个bool意思下
                   // return false;
                }
                foreach (DataRow item in dt.Rows) {
                    Console.WriteLine(item["图片"].ToString());
                }


                    //业务逻辑处理完了就把原来的文件和解压的文件夹删除
                    Directory.Delete(mapPath + "\\" + "filezip", true);
                System.IO.File.Delete(mapPath + "\\" + xlsxFileName);
                //File.Delete(mapPath + "\\" + xlsxFileName);
                System.IO.File.Delete(mapPath + "\\" + zipFileName);
            }
           // return true;
        }

        bool IsRowEmpty(DataRow row)
        {
            foreach (var item in row.ItemArray)
            {
                if (!string.IsNullOrEmpty(item.ToString()))
                {
                    return false; // 只要有一个列不为空,就不是空行
                }
            }
            return true; // 所有列都为空,是空行
        }
        public static string MidStrEx(string sourse, string startstr, string endstr)
        {
            string result = string.Empty;
            int startindex, endindex;
            try
            {
                startindex = sourse.IndexOf(startstr);
                if (startindex == -1)
                    return result;
                string tmpstr = sourse.Substring(startindex + startstr.Length);
                endindex = tmpstr.IndexOf(endstr);
                if (endindex == -1)
                    return result;
                result = tmpstr.Remove(endindex);
            }
            catch (Exception ex)
            {
                Console.Write("MidStrEx Err:" + ex.Message);
            }
            return result;
        }
        /// <summary>
        /// Xml图片表格位置及路径ID
        /// </summary>
        private const string _XmlExcel = @"xl\cellimages.xml";
        /// <summary>
        /// Xml图片路径
        /// </summary>
        private const string _XmlPict = @"xl\_rels\cellimages.xml.rels";

        /// <summary>
        /// Xml图片表格位置及路径ID
        /// </summary>
        private const string _XmlExcelfloat = @"\xl\drawings\drawing1.xml";
        /// <summary>
        /// Xml图片路径
        /// </summary>
        private const string _XmlPictfloat = @"\xl\drawings\_rels\drawing1.xml.rels";


        /// <summary>
        /// 获取图片路径 Xml节点
        /// </summary>
        /// <param name="path">解压后的文件夹路径</param>
        /// <returns></returns>
        private XmlNodeList GetXmlPictNodeList(string path)
        {
            XmlDocument doc = new XmlDocument();
            if (File.Exists(path + _XmlPict)) { 
            
                doc.Load(path + _XmlPict);
                XmlNode root = doc.DocumentElement;
                return root.ChildNodes;
            }
            return null;
        }
        private XmlNodeList GetXmlPictNodeListFloat(string path)
        {
            XmlDocument doc = new XmlDocument();
            if (File.Exists(path + _XmlPictfloat)) { 
                doc.Load(path + _XmlPictfloat);
                XmlNode root = doc.DocumentElement;
                return root.ChildNodes;
            }
            return null;

        }
        /// <summary>
        /// 获取图片表格位置及路径ID Xml节点
        /// </summary>
        /// <param name="path">解压后的文件夹路径</param>
        /// <returns></returns>
        private XmlNodeList GetXmlExclNodeList(string path)
        {
            XmlDocument doc = new XmlDocument();
            if (File.Exists(path + _XmlExcel)) { 
                doc.Load(path + _XmlExcel);
                XmlNode root = doc.DocumentElement;
                return root.ChildNodes;
            }
            return null;

        }
        private XmlNodeList GetXmlExclNodeListFloat(string path)
        {
            XmlDocument doc = new XmlDocument();
            if (File.Exists(path + _XmlExcelfloat))
            {
                doc.Load(path + _XmlExcelfloat);
                XmlNode root = doc.DocumentElement;
                return root.ChildNodes;
            }
            return null;

        }

        /// <summary>
        /// 解压文件
        /// </summary>
        /// <param name="zipFilePath">压缩文件路径</param>
        /// <param name="path">返回压缩文件夹路径</param>
        /// <param name="unZipDir">解压文件存放路径,为空时默认与压缩文件同一级目录下,跟压缩文件同名的文件夹</param>
        /// <returns></returns>
        private bool UnZipFile(string zipFilePath, out string path, string unZipDir = null)
        {
            if (zipFilePath == string.Empty)
            {
                path = null;
                return false;
            }

            if (!System.IO.File.Exists(zipFilePath))
            {
                path = null;
                return false;
            }
            //解压文件夹为空时默认与压缩文件同一级目录下,跟压缩文件同名的文件夹 
            if (string.IsNullOrWhiteSpace(unZipDir))
                unZipDir = zipFilePath.Replace(Path.GetFileName(zipFilePath), Path.GetFileNameWithoutExtension(zipFilePath));

            if (!unZipDir.EndsWith("\\"))
                unZipDir += "\\";

            if (!Directory.Exists(unZipDir))
                Directory.CreateDirectory(unZipDir);
            try
            {
                using (ZipInputStream s = new ZipInputStream(System.IO.File.OpenRead(zipFilePath)))
                {

                    ZipEntry theEntry;
                    while ((theEntry = s.GetNextEntry()) != null)
                    {
                        string directoryName = Path.GetDirectoryName(theEntry.Name);
                        string fileName = Path.GetFileName(theEntry.Name);
                        if (directoryName.Length > 0)
                        {
                            Directory.CreateDirectory(unZipDir + directoryName);
                        }
                        if (!directoryName.EndsWith("\\"))
                            directoryName += "\\";
                        if (fileName != String.Empty)
                        {
                            using (FileStream streamWriter = System.IO.File.Create(unZipDir + theEntry.Name))
                            {

                                int size = 2048;
                                byte[] data = new byte[2048];
                                while (true)
                                {
                                    size = s.Read(data, 0, data.Length);
                                    if (size > 0)
                                    {
                                        streamWriter.Write(data, 0, size);
                                    }
                                    else
                                    {
                                        break;
                                    }
                                }
                            }
                        }
                    }
                }
            }
            catch
            {
                path = null;
                return false;
            }
            path = unZipDir;
            return true;
        }
    }
    /// <summary>
    /// excel 图片信息
    /// </summary>
    public class o_ExcelImgModel
    {
        /// <summary>
        /// ID
        /// </summary>
        public string ID { get; set; }
        /// <summary>
        /// 上传图片生成的id
        /// </summary>
        public string Name { get; set; }
        /// <summary>
        /// 行
        /// </summary>
        public int Row { get; set; }
        /// <summary>
        /// 单元格
        /// </summary>
        public int Col { get; set; }
        /// <summary>
        /// 图片文件绝对路径
        /// </summary>
        public string PathOfPicture { get; set; }
    }
    public class ExcelHelper
    {
        private static IWorkbook workbook = null;
        private static FileStream fs = null;
        /// <summary>
        /// 将excel中的数据导入到DataTable中
        /// </summary>
        /// <param name="fileName">excel文件路径</param>
        /// <param name="sheetName">excel工作薄sheet的名称</param>
        /// <param name="isFirstRowColumn">第一行是否是DataTable的列名</param>
        /// <returns>返回的DataTable</returns>
        public static DataTable ExcelToDataTable(string fileName, string sheetName = null, bool isFirstRowColumn = true)
        {
            ISheet sheet = null;
            DataTable data = new DataTable();
            int startRow = 0;
            try
            {
                fs = new FileStream(fileName, FileMode.Open, FileAccess.Read);
                if (fileName.IndexOf(".xlsx") > 0) // 2007版本
                    workbook = new XSSFWorkbook(fs);
                else if (fileName.IndexOf(".xls") > 0) // 2003版本
                    workbook = new HSSFWorkbook(fs);

                if (sheetName != null)
                {
                    sheet = workbook.GetSheet(sheetName);
                    if (sheet == null) //如果没有找到指定的sheetName对应的sheet,则尝试获取第一个sheet
                    {
                        sheet = workbook.GetSheetAt(0);
                    }
                }
                else
                {
                    sheet = workbook.GetSheetAt(0);
                }
                if (sheet != null)
                {
                    IRow firstRow = sheet.GetRow(0);
                    int cellCount = firstRow.LastCellNum; //一行最后一个cell的编号 即总的列数

                    if (isFirstRowColumn)
                    {
                        for (int i = firstRow.FirstCellNum; i < cellCount; ++i)
                        {
                            ICell cell = firstRow.GetCell(i);
                            if (cell != null)
                            {
                                string cellValue = cell.StringCellValue;
                                if (cellValue != null)
                                {
                                    DataColumn column = new DataColumn(cellValue);
                                    data.Columns.Add(column);
                                }
                            }
                        }
                        startRow = sheet.FirstRowNum + 1;
                    }
                    else
                    {
                        for (int i = firstRow.FirstCellNum; i < cellCount; i++)
                        {
                            DataColumn column = new DataColumn(i.ToString());
                            data.Columns.Add(column);
                        }
                        startRow = sheet.FirstRowNum;
                    }

                    //最后一列的标号
                    int rowCount = sheet.LastRowNum;
                    for (int i = startRow; i <= rowCount; ++i)
                    {
                        IRow row = sheet.GetRow(i);
                        if (row == null) continue; //没有数据的行默认是null       
                        Console.WriteLine("第 " + i + " 行");
                        DataRow dataRow = data.NewRow();
                        if (row.FirstCellNum >= 0) { 
                          for (int j = row.FirstCellNum; j < cellCount; ++j)
                            {
                       
                                if (row.GetCell(j) != null) //同理,没有数据的单元格都默认是null
                                    dataRow[j] = row.GetCell(j).ToString();
                                Console.WriteLine("第" + j + "列");
                            }
                            data.Rows.Add(dataRow);
                        
                        }

                    }
                }

                return data;
            }
            catch (Exception ex)
            {
                Console.WriteLine("Exception: " + ex.Message);
                return null;
            }
        }
    }
}

标签:core,return,string,..,mapPath,var,path,null,图片
From: https://www.cnblogs.com/dopoho/p/18006113

相关文章

  • php下载远程图片保存到本地
    /***下载远程图片保存到本地*@param$url文件url*@param$save_dir保存文件目录*@param$filename保存文件名称*@param$type使用的下载方式*@returnbool*/functiondownloadImage($url,$save_dir='',$filename=''){if(trim($url)==......
  • C# 将 HTML 转换为图片或 PDF
    原文链接:https://blog.csdn.net/slowlifes/article/details/72940116/首先是把HTML转换为图片。publicpartialclassForm1:Form{publicForm1(){InitializeComponent();}WebBrowserwebBrowser=null;......
  • c# 在 word指定位置插入文字和图片(替换 书签)
    原文链接:https://blog.csdn.net/chen1231985111/article/details/125811918使用Microsoft.Office.Interop.Word进行插入,word文件中插入“书签”。在com组件中引用Microsoft.Word.xxx.xx注意下面的坑:1.如果要兼容office2007,自己电脑上需要装个07才行(有可能不需要,我......
  • vue实现v-html渲染的图片预览
    在v-html属性标签的标签上添加getImg方法<divclass="content"v-html="content"@click="getImg($event)"></div>getImg方法,通过$event可获取用户当前点击的元素相应的内容,这里可以获取所点击图片对应的src。判断拿到src后,添加图片的预览效果就可以了//点击查看图片co......
  • PDF转图片
    importfitzdefpdf2img(pdf_path,img_dir):doc=fitz.open(pdf_path)#打开pdfforpageindoc:#遍历pdf的每一页zoom_x=2.0#设置每页的水平缩放因子zoom_y=2.0#设置每页的垂直缩放因子mat=fitz.Matrix(zoom_x,zo......
  • 一次人脸识别ViewFaceCore使用的经验分享,看我把门店淘汰下来的POS机改成了人脸考勤机
    POS软件是什么?你好意思吗,还在用老掉牙的Winform。   门店被淘汰的POS机销售终端——POS(pointofsale)是一种多功能终端,把它安装在信用卡的特约商户和受理网点中与计算机联成网络,就能实现电子资金自动转账,它具有支持消费、预授权、余额查询和转账等功能,使用起来安全、......
  • Dart core library
    DartcorelibraryDartIOclassFile&classDirectory(两个均是继承自abstractFileSystemEntity)FIle仅仅用来操作真正的文件Directory仅仅针对文件夹(即使按照规定Directory也是特殊文件)FileFileReadreadfileasyncvoidmain()async{Filefil......
  • AI生成的图片是否具有版权:如何认定美术作品的“抄袭”行为?
    相关:实务丨如何认定美术作品的“抄袭”行为?首先,我认为AI生成的图片是否具有版权这个问题就不是一个问题,或者说这不是一个正确的提法,应该说AI生成的某张图片是否具有版权?也可以说,AI生成的某张图片是否侵权?因为,不把问题具体到具体的某张图片上,这个问题是没有讨论的前提的,还有,......
  • springboot上传图片到阿里云
    1.登录注册 购买oss服务2.创建Bucket3.获取accesskey4.编写阿里云上传工具类publicclassAliOssUtil{privatestaticfinalStringENDPOINT="https://oss-cn-beijing.aliyuncs.com";privatestaticfinalStringACCESS_KEY_ID="填写自己的accesskey";......
  • Linux批量转换图片文件(png/jpg)
    ImageMagick转换图片一、convert命令Version:ImageMagick6.9.11-60Q16x86_642021-01-25https://imagemagick.orgCopyright:(C)1999-2021ImageMagickStudioLLCLicense:https://imagemagick.org/script/license.phpFeatures:CipherDPCModulesOpenMP(4.5)Delega......