使用NPOI读取word表格里面的图片

一、引用NuGetGet里的npoi,如下图:

 二、打开文件

Stream stream = File.OpenRead(@"C:\Test\\11.docx");
XWPFDocument doc = new XWPFDocument(stream);

三、获取word里面所有的表格

var allTables = doc.Tables;

四、获得表格的所有行

var rows = table.Rows;

五、获得行下的所有列

var cells = row.GetTableCells();

六、获得列里的图片

var run = cell.Paragraphs[0].Runs[0];
List<XWPFPicture> xwpfPictureList = run.GetEmbeddedPictures();

七、得到图片的二进制数据

var data = xwpfPictureList[0].GetPictureData();
var picData = data.Data;

八、把二进制转换为image并保存到本地

var image = GetImageFromByte(picData);
image.Save(@"C:\Test\pics\\0603-" + i + ".png");

 

下面是完整的代码:

                Stream stream = File.OpenRead(@"C:\Test\\11.docx");
                XWPFDocument doc = new XWPFDocument(stream);
                var allTables = doc.Tables;
                int i = 1;
                foreach (var table in allTables)
                {
                    var rows = table.Rows;
                    foreach (var row in rows)
                    {
                        var cells = row.GetTableCells();
                        foreach (var cell in cells)
                        {
                            if (cell.Paragraphs[0].Runs.Count > 0)
                            {
                                var run = cell.Paragraphs[0].Runs[0];
                                List<XWPFPicture> xwpfPictureList = run.GetEmbeddedPictures();
                                if (xwpfPictureList.Count > 0)
                                {
                                    var data = xwpfPictureList[0].GetPictureData();
                                    var picData = data.Data;
                                    var image = GetImageFromByte(picData);
                                    image.Save(@"C:\Test\pics\\0603-" + i + ".png");
                                    i++;
                                }
                            }
                        }
                    }

                }
        public System.Drawing.Image GetImageFromByte(byte[] streamByte)
        {
            System.IO.MemoryStream ms = new System.IO.MemoryStream(streamByte);
            System.Drawing.Image img = System.Drawing.Image.FromStream(ms);
            return img;
        }

 

posted @ 2020-06-03 10:12  星星c#  阅读(2424)  评论(1编辑  收藏  举报