使用net core 6 c# 的 NPOI 包,讀取excel..xlsx單元格內的圖片,並儲存到指定伺服器

2022-07-01 15:00:45

這個是記錄,單元格的圖片。

 

直接上程式碼,直接新建一個 net core api 解決方案,參照一下nuget包。本地建立一個 .xlsx 格式的excel檔案

using ICSharpCode.SharpZipLib.Zip;
using Microsoft.AspNetCore.Mvc;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using System.Data;
using System.Xml;

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

        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 = _hostingEnvironment.ContentRootPath;
            //業務邏輯處理完了就把原來的檔案和解壓的資料夾刪除
            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 bool ImportExcel_Img(IFormFileCollection files)
        {

            if (files.Count > 0)
            {
                var file = files[0];
                //讀取匯入的檔案型別
                var fileExt = file.FileName.Substring(file.FileName.LastIndexOf('.')).ToLower();
                if (!fileExt.Equals(".xlsx"))
                {
                    //提示檔案型別不正確
                    return false;
                }
                //轉換儲存zip
                string zipFileName = "filezip" + ".zip";
                string xlsxFileName = "filexlsx" + ".xlsx";
                var mapPath = _hostingEnvironment.ContentRootPath;
                //儲存xlsx到伺服器
                using (var stream = new FileStream(mapPath + xlsxFileName, FileMode.OpenOrCreate, FileAccess.ReadWrite))
                {
                    file.CopyToAsync(stream);
                }

                //儲存zip到伺服器
                using (var stream = new FileStream(mapPath  + zipFileName, FileMode.OpenOrCreate, FileAccess.ReadWrite))
                {
                    file.CopyToAsync(stream);
                }
                var dt = ExcelHelper.ExcelToDataTable(mapPath + xlsxFileName);
                //解壓,如果解壓成功則根據xml處理 (應為方便我就放在ExcelHelper裡面了)
                if (UnZipFile(mapPath + zipFileName, out string path))
                {
                    //excel 圖片資訊
                    List<o_ExcelImgModel> o_ExcelImgModelList = new List<o_ExcelImgModel>();
                    //圖片路徑資料夾
                    var mediaFolderPath = path + @"xl\media";
                    //判斷是否存在此資料夾如果有則處理(如果沒有圖片他是不會有這個資料夾的)
                    if (System.IO.Directory.Exists(mediaFolderPath))
                    {
                        //解壓成功獲取xml 節點做處理
                        var exclNode = GetXmlExclNodeList(path);
                        var pictNode = GetXmlPictNodeList(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  圖片路徑取到了,此時你可以儲存了
                        }
                    }
                    //現在dt某一列存放了圖片的絕對路徑就可以通過table去處理了
                    //迴圈表插入資料及上傳
                    foreach (DataRow item in dt.Rows)
                    {
                        //此時你excel轉換的 dataTable表的圖片欄位的 值是:"_xlfn.DISPIMG(\"ID_CD49305586E940EF8F78CD3B54A4BCD3\",1)"
                        item["使用者名稱"].ToString(); //"zhao1"

                        //var kkl= item["IMG"].ToString(); //  "_xlfn.DISPIMG(\"ID_CD49305586E940EF8F78CD3B54A4BCD3\",1)"
                        var breakApart = item["IMG"].ToString().Split('\\', '"')[1];
                        var imgPath= o_ExcelImgModelList.FirstOrDefault(x => x.Name == breakApart);

                        //獲取圖片然後做上傳邏輯,這個自己實現我就不多講了
                    }
                }
                else
                {
                    //解壓時報直接返回,這個返回啥型別或者啥資料自己定義就好我這邊demo 隨緣來個bool意思下
                    return false;
                }
                //業務邏輯處理完了就把原來的檔案和解壓的資料夾刪除
                Directory.Delete(mapPath + "\\" + "filezip", true);
                System.IO.File.Delete(mapPath + "\\" + xlsxFileName);
                //File.Delete(mapPath + "\\" + xlsxFileName);
                System.IO.File.Delete(mapPath + "\\" + zipFileName);
            }
            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節點
        /// </summary>
        /// <param name="path">解壓後的資料夾路徑</param>
        /// <returns></returns>
        private XmlNodeList GetXmlPictNodeList(string path)
        {
            XmlDocument doc = new XmlDocument();
            doc.Load(path + _XmlPict);
            XmlNode root = doc.DocumentElement;
            return root.ChildNodes;
        }

        /// <summary>
        /// 獲取圖片表格位置及路徑ID Xml節點
        /// </summary>
        /// <param name="path">解壓後的資料夾路徑</param>
        /// <returns></returns>
        private XmlNodeList GetXmlExclNodeList(string path)
        {
            XmlDocument doc = new XmlDocument();
            doc.Load(path + _XmlExcel);
            XmlNode root = doc.DocumentElement;
            return root.ChildNodes;
        }
        /// <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 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       

                        DataRow dataRow = data.NewRow();
                        for (int j = row.FirstCellNum; j < cellCount; ++j)
                        {
                            if (row.GetCell(j) != null) //同理,沒有資料的單元格都預設是null
                                dataRow[j] = row.GetCell(j).ToString();
                        }
                        data.Rows.Add(dataRow);
                    }
                }

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

 

簡單記錄一下,有問題的,可以留言,看到就回復