简体   繁体   English

使用NPOI从Excel文件读取图像

[英]Read Image From Excel File Using NPOI

I'm writing a program in Visual Studio 2010 using C# to read some excel file, and I'm using the NPOI library. 我正在Visual Studio 2010中使用C#编写程序以读取一些excel文件,并且正在使用NPOI库。

The ultimate goal is to read a image in the original excel file(xlsm), copy and paste that image into the new excel file(xlsx). 最终目标是读取原始excel文件(xlsm)中的图像,然后将该图像复制并粘贴到新的excel文件(xlsx)中。 If it can be paste onto the same location as in the original that would be even better. 如果可以将其粘贴到与原始位置相同的位置,那会更好。

I couldn't figure out a way to copy and past directly, so my work-around is to read the image, save a copy of the image locally (as jpeg or something other), then insert the image to the new excel file. 我无法找到直接复制和粘贴的方法,所以我的解决方法是读取图像,在本地保存图像的副本(如jpeg或其他格式),然后将图像插入新的excel文件。

Below is the code I use to read image and save copy. 以下是我用于读取图像和保存副本的代码。

var lst = originalWorkbook.GetAllPictures();
for (int i = 0; i < lst.Count; i++)
{
    var pic = lst[i];
    Stream s = File.Open(String.Format("{0}.jpeg", n), FileMode.Create);
    BinaryFormatter bf = new BinaryFormatter ();
    bf.Serialize(s, pic);
    s.Close();
}

When I ran the program, I'm getting an exception saying " Type 'NPOI.XXSF.UserModel.XSSFPictureData' in Assebly......is not marked as serializable ". 当我运行程序时,出现一个异常,说“ Type 'NPOI.XXSF.UserModel.XSSFPictureData' in Assebly......is not marked as serializable ”。 I tried adding [Serializable] before my class, but the exception still exist. 我尝试在课前添加[Serializable] ,但该异常仍然存在。

How can I fix this serializable issue? 如何解决可序列化的问题? Or is there a better way for me to achieve my ultimate goal? 还是我有更好的方法实现自己的最终目标?

Any help is appreciated. 任何帮助表示赞赏。 Thanks! 谢谢!

Okay, so I figured out a way to save the images locally. 好的,所以我想出了一种在本地保存图像的方法。

var lst = originalWorkbook.GetAllPictures();
for (int i = 0; i < lst.Count; i++)
{
    var pic = (XSSFPictureData) lst[i];
    byte[] data = pic.Data;
    BinaryWriter writer = new BinaryWriter(File.OpenWrite(String.Format("{0}.jpeg", i)));
    writer.Write(data);
    writer.Flush();
    writer.Close();
}

Using the above code, I was able to successfully save all images locally as jpeg files. 使用上面的代码,我能够将所有图像成功地本地保存为jpeg文件。

However, if anyone knows a better or simpler way to copy image from one excel file to another, please help out and answer! 但是,如果有人知道将图像从一个excel文件复制到另一个的更好或更简单的方法,请帮忙并回答!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM