1. 程式人生 > WINDOWS開發 >C# 匯入Excel讀取圖片上傳伺服器或OSS

C# 匯入Excel讀取圖片上傳伺服器或OSS

前言:

  相信很多小夥伴都對匯入Excel很熟悉,但是怎麼把Excel裡某一列的圖片上傳到伺服器或OSS上,在本章節重點講解如何讀取Excel圖片上傳。

一、Excel匯入資料到資料庫

1.準備好Excel讀取的幫助類

在 NuGet 安裝 NPOI.dll

using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using System;
using System.Data;
using System.IO;

namespace ImportExcel.Api.Helper
{
    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;
            }
        }
    }
}

2.讀取Excel資料匯入資料庫(回顧下我們常用的做法,讀取了Excel就存到資料庫)

using ImportExcel.Api.Helper;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web;
using System.Web.Http;

namespace ImportExcel.Api.Controllers
{
    public class ImportExcelController : ApiController
    {

        public bool ImportExcel_Img()
        {

            HttpFileCollection files = HttpContext.Current.Request.Files;
            if (files.Count > 0)
            {
                HttpPostedFile file = files[0];
                string saveTempPath = "~/Temp/Order";
                //讀取匯入的檔案型別
                var fileExt = file.FileName.Substring(file.FileName.LastIndexOf(‘.‘)).ToLower();
                if (!fileExt.Equals(".xlsx"))
                {
                    //提示檔案型別不正確
                    return false;
                }

                var fileName = Guid.NewGuid();
                string xlsxFileName = fileName + ".xlsx";
                var mapPath = HttpContext.Current.Server.MapPath(saveTempPath);
                file.SaveAs(mapPath + @"\" + xlsxFileName);
                var dt = ExcelHelper.ExcelToDataTable(mapPath + @"\" + xlsxFileName);
                if (dt != null)
                {
                    //寫入資料庫邏輯和判斷
                }
            }
            return true;
        }
    }
}

二、Excel匯入資料到資料庫並讀取圖片圖文講解(重點來了)
1.把xlsx檔案改為zip檔案解壓到當前目錄

技術分享圖片

技術分享圖片

2.進入解壓後的目錄找到xml檔案

圖片存放路徑XML:\test\xl\drawings\_rels\drawing1.xml.rels
技術分享圖片

前面我們Excel有四張圖片這裡也會顯示4張圖片的路徑,通過這個Xml可以知道我們圖片存放在哪(注意Id="" 這個地方下面會用到)

訪問圖片資料夾:\test\xl\media

技術分享圖片

圖片拿到了是不是想問怎麼知道這個圖片在哪一列上面呢,別急還有一個Xml檔案可以獲取當前圖片所在單元格與行

獲取當前圖片所在單元格與行Xml:\test\\xl\drawings\drawing1.xml

技術分享圖片

講解到現在相信大家有個底了,怎麼去獲取圖片,圖片對應哪一行哪一列!

三、Excel匯入資料到資料庫並且獲取圖片程式碼實現與講解

在做之前我們先準備以下東西
1.讀取Excel資料的方法(已經有了)
2.解壓zip方法

需要用到的ICSharpCode.SharpZipLib.Zip.dll

/// <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,data.Length);
                                    if (size > 0)
                                    {
                                        streamWriter.Write(data,size);
                                    }
                                    else
                                    {
                                        break;
                                    }
                                }
                            }
                        }
                    }
                }
            }
            catch
            {
                path = null;
                return false;
            }
            path = unZipDir;
            return true;
        }

在實現Excel匯入資料到資料庫的方法做修改

1.準備讀取xml的圖片資訊類

namespace ImportExcel.Api.Model
{
    /// <summary>
    /// excel 圖片資訊
    /// </summary>
    public class o_ExcelImgModel
    {
        /// <summary>
        /// ID
        /// </summary>
        public string ID { get; set; }
        /// <summary>
        /// 行
        /// </summary>
        public int Row { get; set; }
        /// <summary>
        /// 單元格
        /// </summary>
        public int Col { get; set; }
        /// <summary>
        /// 圖片檔案絕對路徑
        /// </summary>
        public string PathOfPicture { get; set; }
    }
}

2.重點程式碼演示

using ImportExcel.Api.Helper;
using ImportExcel.Api.Model;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web;
using System.Web.Http;
using System.Xml;

namespace ImportExcel.Api.Controllers
{
    public class ImportExcelController : ApiController
    {

        public bool ImportExcel_Img()
        {

            HttpFileCollection files = HttpContext.Current.Request.Files;
            if (files.Count > 0)
            {
                HttpPostedFile file = files[0];
                string saveTempPath = "~/Temp/Order";
                //讀取匯入的檔案型別
                var fileExt = file.FileName.Substring(file.FileName.LastIndexOf(‘.‘)).ToLower();
                if (!fileExt.Equals(".xlsx"))
                {
                    //提示檔案型別不正確
                    return false;
                }

                //轉換儲存zip
                var fileName = Guid.NewGuid();
                string zipFileName = fileName + ".zip";
                string xlsxFileName = fileName + ".xlsx";
                var mapPath = HttpContext.Current.Server.MapPath(saveTempPath);
                //儲存xlsx到伺服器
                file.SaveAs(mapPath + "\\" + xlsxFileName);
                //儲存zip到伺服器
                file.SaveAs(mapPath + "\\" + zipFileName);
                var dt = ExcelHelper.ExcelToDataTable(mapPath + @"\" + xlsxFileName);
                //解壓,如果解壓成功則根據xml處理 (應為方便我就放在ExcelHelper裡面了)
                if (ExcelHelper.UnZipFile(HttpContext.Current.Server.MapPath(saveTempPath) + "\\" + zipFileName,out string path))
                {
                    //圖片路徑資料夾
                    var mediaFolderPath = path + "\\xl\\media";
                    //判斷是否存在此資料夾如果有則處理(如果沒有圖片他是不會有這個資料夾的)
                    if (System.IO.Directory.Exists(mediaFolderPath))
                    {
                        //解壓成功獲取xml 節點做處理
                        var exclNode = GetXmlExclNodeList(path);
                        var pictNode = GetXmlPictNodeList(path);
                        //excel 圖片資訊
                        List<o_ExcelImgModel> o_ExcelImgModelList = new List<o_ExcelImgModel>();
                        //獲取圖片資訊與地址
                        foreach (var nl in exclNode)
                        {
                            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 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,Col = col,Row = row,PathOfPicture = pathOfPicture
                                    });

                                    break;
                                }
                            }
                        }
                        //圖片對應dt的哪一列,存到dt然後再迴圈dt去處理(這個是小編的思維,如果有更好的做法可以隨緣發揮)
                        foreach (var item in o_ExcelImgModelList)
                        {
                            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)
                    {
                        //獲取圖片然後做上傳邏輯,這個自己實現我就不多講了
                    }
                }
                else {
                    //解壓時報直接返回,這個返回啥型別或者啥資料自己定義就好我這邊demo 隨緣來個bool意思下
                    return false;
                }
                //業務邏輯處理完了就把原來的檔案和解壓的資料夾刪除
                Directory.Delete(mapPath + "\\" + fileName,true);
                File.Delete(mapPath + "\\" + xlsxFileName);
                File.Delete(mapPath + "\\" + zipFileName);
            }
            return true;
        }
        /// <summary>
        /// Xml圖片表格位置及路徑ID
        /// </summary>
        private const string _XmlExcel = @"\xl\drawings\drawing1.xml";
        /// <summary>
        /// Xml圖片路徑
        /// </summary>
        private const string _XmlPict = @"\xl\drawings\_rels\drawing1.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;
        }

    }
}

  

請認真看程式碼的備註資訊,小編這邊提供的基本都是思路,剩下的要需要小夥伴們自由發揮

文章參考:https://www.jeremyjone.com/395/