• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

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

武飞扬头像
畅聊科技
帮助1

这个是记录,单元格的图片。

学新通

  1.  
    using ICSharpCode.SharpZipLib.Zip;
  2.  
    using Microsoft.AspNetCore.Mvc;
  3.  
    using NPOI.HSSF.UserModel;
  4.  
    using NPOI.SS.UserModel;
  5.  
    using NPOI.XSSF.UserModel;
  6.  
    using System.Data;
  7.  
    using System.Xml;
  8.  
     
  9.  
    namespace ExcelOption.Controllers
  10.  
    {
  11.  
    [ApiController]
  12.  
    [Route("[controller]")]
  13.  
    public class ImportExcelController : ControllerBase
  14.  
    {
  15.  
     
  16.  
    private readonly Microsoft.AspNetCore.Hosting.IHostingEnvironment _hostingEnvironment;
  17.  
     
  18.  
    public ImportExcelController(Microsoft.AspNetCore.Hosting.IHostingEnvironment hostingEnvironment)
  19.  
    {
  20.  
    _hostingEnvironment = hostingEnvironment;
  21.  
    }
  22.  
     
  23.  
    [HttpGet(Name = "dele")]
  24.  
    public bool dele()
  25.  
    {
  26.  
    string zipFileName = "filezip" ".zip";
  27.  
    string xlsxFileName = "filexlsx" ".xlsx";
  28.  
    var mapPath = _hostingEnvironment.ContentRootPath;
  29.  
    //业务逻辑处理完了就把原来的文件和解压的文件夹删除
  30.  
    Directory.Delete(mapPath @"\" "filezip", true);
  31.  
    System.IO.File.Delete(mapPath @"\" xlsxFileName);
  32.  
    //File.Delete(mapPath "\\" xlsxFileName);
  33.  
    System.IO.File.Delete(mapPath @"\" zipFileName);
  34.  
     
  35.  
    return true;
  36.  
    }
  37.  
     
  38.  
    [HttpPost(Name = "ImportExcel_Img")]
  39.  
    public bool ImportExcel_Img(IFormFileCollection files)
  40.  
    {
  41.  
     
  42.  
    if (files.Count > 0)
  43.  
    {
  44.  
    var file = files[0];
  45.  
    //读取导入的文件类型
  46.  
    var fileExt = file.FileName.Substring(file.FileName.LastIndexOf('.')).ToLower();
  47.  
    if (!fileExt.Equals(".xlsx"))
  48.  
    {
  49.  
    //提示文件类型不正确
  50.  
    return false;
  51.  
    }
  52.  
    //转换保存zip
  53.  
    string zipFileName = "filezip" ".zip";
  54.  
    string xlsxFileName = "filexlsx" ".xlsx";
  55.  
    var mapPath = _hostingEnvironment.ContentRootPath;
  56.  
    //保存xlsx到服务器
  57.  
    using (var stream = new FileStream(mapPath xlsxFileName, FileMode.OpenOrCreate, FileAccess.ReadWrite))
  58.  
    {
  59.  
    file.CopyToAsync(stream);
  60.  
    }
  61.  
     
  62.  
    //保存zip到服务器
  63.  
    using (var stream = new FileStream(mapPath zipFileName, FileMode.OpenOrCreate, FileAccess.ReadWrite))
  64.  
    {
  65.  
    file.CopyToAsync(stream);
  66.  
    }
  67.  
    var dt = ExcelHelper.ExcelToDataTable(mapPath xlsxFileName);
  68.  
    //解压,如果解压成功则根据xml处理 (应为方便我就放在ExcelHelper里面了)
  69.  
    if (UnZipFile(mapPath zipFileName, out string path))
  70.  
    {
  71.  
    //excel 图片信息
  72.  
    List<o_ExcelImgModel> o_ExcelImgModelList = new List<o_ExcelImgModel>();
  73.  
    //图片路径文件夹
  74.  
    var mediaFolderPath = path @"xl\media";
  75.  
    //判断是否存在此文件夹如果有则处理(如果没有图片他是不会有这个文件夹的)
  76.  
    if (System.IO.Directory.Exists(mediaFolderPath))
  77.  
    {
  78.  
    //解压成功获取xml 节点做处理
  79.  
    var exclNode = GetXmlExclNodeList(path);
  80.  
    var pictNode = GetXmlPictNodeList(path);
  81.  
     
  82.  
    //获取图片信息与地址
  83.  
    foreach (var nl in exclNode)
  84.  
    {
  85.  
    XmlElement sondNode = (XmlElement)nl;
  86.  
    XmlNodeList descendDodeList = sondNode.ChildNodes;
  87.  
    XmlNodeList picNodeList = descendDodeList[0].ChildNodes;
  88.  
     
  89.  
     
  90.  
    XmlNodeList nvPicPrNodeList = picNodeList[0].ChildNodes;
  91.  
    XmlElement cNvPrElement = (XmlElement)nvPicPrNodeList.Item(0);
  92.  
    string name = cNvPrElement.GetAttribute("name").ToString();
  93.  
     
  94.  
     
  95.  
    XmlNodeList blipFillNodeList = picNodeList[1].ChildNodes;
  96.  
    XmlElement picElement = (XmlElement)blipFillNodeList.Item(0);
  97.  
    string id = picElement.GetAttribute("r:embed").ToString();
  98.  
     
  99.  
     
  100.  
    foreach (XmlNode xn in pictNode)
  101.  
    {
  102.  
    XmlElement xe = (XmlElement)xn;
  103.  
    if (xe.GetAttribute("Id").ToString() == id)
  104.  
    {
  105.  
    var pathOfPicture = xe.GetAttribute("Target").ToString().Replace("..", "").Replace("/", @"\");
  106.  
    pathOfPicture = path @"xl\" pathOfPicture;
  107.  
    o_ExcelImgModelList.Add(new o_ExcelImgModel()
  108.  
    {
  109.  
    ID = id,
  110.  
    Name = name,
  111.  
    PathOfPicture = pathOfPicture
  112.  
    });
  113.  
    break;
  114.  
    }
  115.  
    }
  116.  
    }
  117.  
    //图片对应dt的哪一列,存到dt然后再循环dt去处理(这个是小编的思维,如果有更好的做法可以随缘发挥)
  118.  
    foreach (var item in o_ExcelImgModelList)
  119.  
    {
  120.  
    //item.PathOfPicture 图片路径取到了,此时你可以存储了
  121.  
    }
  122.  
    }
  123.  
    //现在dt某一列存放了图片的绝对路径就可以通过table去处理了
  124.  
    //循环表插入数据及上传
  125.  
    foreach (DataRow item in dt.Rows)
  126.  
    {
  127.  
    //此时你excel转换的 dataTable表的图片字段的 值是:"_xlfn.DISPIMG(\"ID_CD49305586E940EF8F78CD3B54A4BCD3\",1)"
  128.  
    item["用户名"].ToString(); //"zhao1"
  129.  
     
  130.  
    //var kkl= item["IMG"].ToString(); // "_xlfn.DISPIMG(\"ID_CD49305586E940EF8F78CD3B54A4BCD3\",1)"
  131.  
    var breakApart = item["IMG"].ToString().Split('\\', '"')[1];
  132.  
    var imgPath= o_ExcelImgModelList.FirstOrDefault(x => x.Name == breakApart);
  133.  
     
  134.  
    //获取图片然后做上传逻辑,这个自己实现我就不多讲了
  135.  
    }
  136.  
    }
  137.  
    else
  138.  
    {
  139.  
    //解压时报直接返回,这个返回啥类型或者啥数据自己定义就好我这边demo 随缘来个bool意思下
  140.  
    return false;
  141.  
    }
  142.  
    //业务逻辑处理完了就把原来的文件和解压的文件夹删除
  143.  
    Directory.Delete(mapPath "\\" "filezip", true);
  144.  
    System.IO.File.Delete(mapPath "\\" xlsxFileName);
  145.  
    //File.Delete(mapPath "\\" xlsxFileName);
  146.  
    System.IO.File.Delete(mapPath "\\" zipFileName);
  147.  
    }
  148.  
    return true;
  149.  
    }
  150.  
    public static string MidStrEx(string sourse, string startstr, string endstr)
  151.  
    {
  152.  
    string result = string.Empty;
  153.  
    int startindex, endindex;
  154.  
    try
  155.  
    {
  156.  
    startindex = sourse.IndexOf(startstr);
  157.  
    if (startindex == -1)
  158.  
    return result;
  159.  
    string tmpstr = sourse.Substring(startindex startstr.Length);
  160.  
    endindex = tmpstr.IndexOf(endstr);
  161.  
    if (endindex == -1)
  162.  
    return result;
  163.  
    result = tmpstr.Remove(endindex);
  164.  
    }
  165.  
    catch (Exception ex)
  166.  
    {
  167.  
    Console.Write("MidStrEx Err:" ex.Message);
  168.  
    }
  169.  
    return result;
  170.  
    }
  171.  
    /// <summary>
  172.  
    /// Xml图片表格位置及路径ID
  173.  
    /// </summary>
  174.  
    private const string _XmlExcel = @"xl\cellimages.xml";
  175.  
    /// <summary>
  176.  
    /// Xml图片路径
  177.  
    /// </summary>
  178.  
    private const string _XmlPict = @"xl\_rels\cellimages.xml.rels";
  179.  
     
  180.  
    /// <summary>
  181.  
    /// 获取图片路径 Xml节点
  182.  
    /// </summary>
  183.  
    /// <param name="path">解压后的文件夹路径</param>
  184.  
    /// <returns></returns>
  185.  
    private XmlNodeList GetXmlPictNodeList(string path)
  186.  
    {
  187.  
    XmlDocument doc = new XmlDocument();
  188.  
    doc.Load(path _XmlPict);
  189.  
    XmlNode root = doc.DocumentElement;
  190.  
    return root.ChildNodes;
  191.  
    }
  192.  
     
  193.  
    /// <summary>
  194.  
    /// 获取图片表格位置及路径ID Xml节点
  195.  
    /// </summary>
  196.  
    /// <param name="path">解压后的文件夹路径</param>
  197.  
    /// <returns></returns>
  198.  
    private XmlNodeList GetXmlExclNodeList(string path)
  199.  
    {
  200.  
    XmlDocument doc = new XmlDocument();
  201.  
    doc.Load(path _XmlExcel);
  202.  
    XmlNode root = doc.DocumentElement;
  203.  
    return root.ChildNodes;
  204.  
    }
  205.  
    /// <summary>
  206.  
    /// 解压文件
  207.  
    /// </summary>
  208.  
    /// <param name="zipFilePath">压缩文件路径</param>
  209.  
    /// <param name="path">返回压缩文件夹路径</param>
  210.  
    /// <param name="unZipDir">解压文件存放路径,为空时默认与压缩文件同一级目录下,跟压缩文件同名的文件夹</param>
  211.  
    /// <returns></returns>
  212.  
    private bool UnZipFile(string zipFilePath, out string path, string unZipDir = null)
  213.  
    {
  214.  
    if (zipFilePath == string.Empty)
  215.  
    {
  216.  
    path = null;
  217.  
    return false;
  218.  
    }
  219.  
     
  220.  
    if (!System.IO.File.Exists(zipFilePath))
  221.  
    {
  222.  
    path = null;
  223.  
    return false;
  224.  
    }
  225.  
    //解压文件夹为空时默认与压缩文件同一级目录下,跟压缩文件同名的文件夹
  226.  
    if (string.IsNullOrWhiteSpace(unZipDir))
  227.  
    unZipDir = zipFilePath.Replace(Path.GetFileName(zipFilePath), Path.GetFileNameWithoutExtension(zipFilePath));
  228.  
     
  229.  
    if (!unZipDir.EndsWith("\\"))
  230.  
    unZipDir = "\\";
  231.  
     
  232.  
    if (!Directory.Exists(unZipDir))
  233.  
    Directory.CreateDirectory(unZipDir);
  234.  
    try
  235.  
    {
  236.  
    using (ZipInputStream s = new ZipInputStream(System.IO.File.OpenRead(zipFilePath)))
  237.  
    {
  238.  
     
  239.  
    ZipEntry theEntry;
  240.  
    while ((theEntry = s.GetNextEntry()) != null)
  241.  
    {
  242.  
    string directoryName = Path.GetDirectoryName(theEntry.Name);
  243.  
    string fileName = Path.GetFileName(theEntry.Name);
  244.  
    if (directoryName.Length > 0)
  245.  
    {
  246.  
    Directory.CreateDirectory(unZipDir directoryName);
  247.  
    }
  248.  
    if (!directoryName.EndsWith("\\"))
  249.  
    directoryName = "\\";
  250.  
    if (fileName != String.Empty)
  251.  
    {
  252.  
    using (FileStream streamWriter = System.IO.File.Create(unZipDir theEntry.Name))
  253.  
    {
  254.  
     
  255.  
    int size = 2048;
  256.  
    byte[] data = new byte[2048];
  257.  
    while (true)
  258.  
    {
  259.  
    size = s.Read(data, 0, data.Length);
  260.  
    if (size > 0)
  261.  
    {
  262.  
    streamWriter.Write(data, 0, size);
  263.  
    }
  264.  
    else
  265.  
    {
  266.  
    break;
  267.  
    }
  268.  
    }
  269.  
    }
  270.  
    }
  271.  
    }
  272.  
    }
  273.  
    }
  274.  
    catch
  275.  
    {
  276.  
    path = null;
  277.  
    return false;
  278.  
    }
  279.  
    path = unZipDir;
  280.  
    return true;
  281.  
    }
  282.  
    }
  283.  
    /// <summary>
  284.  
    /// excel 图片信息
  285.  
    /// </summary>
  286.  
    public class o_ExcelImgModel
  287.  
    {
  288.  
    /// <summary>
  289.  
    /// ID
  290.  
    /// </summary>
  291.  
    public string ID { get; set; }
  292.  
    /// <summary>
  293.  
    /// 上传图片生成的id
  294.  
    /// </summary>
  295.  
    public string Name { get; set; }
  296.  
    /// <summary>
  297.  
    /// 图片文件绝对路径
  298.  
    /// </summary>
  299.  
    public string PathOfPicture { get; set; }
  300.  
    }
  301.  
    public class ExcelHelper
  302.  
    {
  303.  
    private static IWorkbook workbook = null;
  304.  
    private static FileStream fs = null;
  305.  
    /// <summary>
  306.  
    /// 将excel中的数据导入到DataTable中
  307.  
    /// </summary>
  308.  
    /// <param name="fileName">excel文件路径</param>
  309.  
    /// <param name="sheetName">excel工作薄sheet的名称</param>
  310.  
    /// <param name="isFirstRowColumn">第一行是否是DataTable的列名</param>
  311.  
    /// <returns>返回的DataTable</returns>
  312.  
    public static DataTable ExcelToDataTable(string fileName, string sheetName = null, bool isFirstRowColumn = true)
  313.  
    {
  314.  
    ISheet sheet = null;
  315.  
    DataTable data = new DataTable();
  316.  
    int startRow = 0;
  317.  
    try
  318.  
    {
  319.  
    fs = new FileStream(fileName, FileMode.Open, FileAccess.Read);
  320.  
    if (fileName.IndexOf(".xlsx") > 0) // 2007版本
  321.  
    workbook = new XSSFWorkbook(fs);
  322.  
    else if (fileName.IndexOf(".xls") > 0) // 2003版本
  323.  
    workbook = new HSSFWorkbook(fs);
  324.  
     
  325.  
    if (sheetName != null)
  326.  
    {
  327.  
    sheet = workbook.GetSheet(sheetName);
  328.  
    if (sheet == null) //如果没有找到指定的sheetName对应的sheet,则尝试获取第一个sheet
  329.  
    {
  330.  
    sheet = workbook.GetSheetAt(0);
  331.  
    }
  332.  
    }
  333.  
    else
  334.  
    {
  335.  
    sheet = workbook.GetSheetAt(0);
  336.  
    }
  337.  
    if (sheet != null)
  338.  
    {
  339.  
    IRow firstRow = sheet.GetRow(0);
  340.  
    int cellCount = firstRow.LastCellNum; //一行最后一个cell的编号 即总的列数
  341.  
     
  342.  
    if (isFirstRowColumn)
  343.  
    {
  344.  
    for (int i = firstRow.FirstCellNum; i < cellCount; i)
  345.  
    {
  346.  
    ICell cell = firstRow.GetCell(i);
  347.  
    if (cell != null)
  348.  
    {
  349.  
    string cellValue = cell.StringCellValue;
  350.  
    if (cellValue != null)
  351.  
    {
  352.  
    DataColumn column = new DataColumn(cellValue);
  353.  
    data.Columns.Add(column);
  354.  
    }
  355.  
    }
  356.  
    }
  357.  
    startRow = sheet.FirstRowNum 1;
  358.  
    }
  359.  
    else
  360.  
    {
  361.  
    for (int i = firstRow.FirstCellNum; i < cellCount; i )
  362.  
    {
  363.  
    DataColumn column = new DataColumn(i.ToString());
  364.  
    data.Columns.Add(column);
  365.  
    }
  366.  
    startRow = sheet.FirstRowNum;
  367.  
    }
  368.  
     
  369.  
    //最后一列的标号
  370.  
    int rowCount = sheet.LastRowNum;
  371.  
    for (int i = startRow; i <= rowCount; i)
  372.  
    {
  373.  
    IRow row = sheet.GetRow(i);
  374.  
    if (row == null) continue; //没有数据的行默认是null       
  375.  
     
  376.  
    DataRow dataRow = data.NewRow();
  377.  
    for (int j = row.FirstCellNum; j < cellCount; j)
  378.  
    {
  379.  
    if (row.GetCell(j) != null) //同理,没有数据的单元格都默认是null
  380.  
    dataRow[j] = row.GetCell(j).ToString();
  381.  
    }
  382.  
    data.Rows.Add(dataRow);
  383.  
    }
  384.  
    }
  385.  
     
  386.  
    return data;
  387.  
    }
  388.  
    catch (Exception ex)
  389.  
    {
  390.  
    Console.WriteLine("Exception: " ex.Message);
  391.  
    return null;
  392.  
    }
  393.  
    }
  394.  
    }
  395.  
    }
学新通

简单记录一下,有问题的,可以留言,看到就回复

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /boutique/detail/tanhgfkcbg
系列文章
更多 icon
同类精品
更多 icon
继续加载